C
C#4mo ago
ikalou.

Casting from int to uint and back

Is casting a negative int to a uint and then back to a int guaranteed to give back the original negative value on all platforms, architectures and runtimes? Thanks!
8 Replies
MODiX
MODiX4mo ago
Angius
REPL Result: Failure
(uint)-17
(uint)-17
Exception: CompilationErrorException
- Constant value '-17' cannot be converted to a 'uint' (use 'unchecked' syntax to override)
- Constant value '-17' cannot be converted to a 'uint' (use 'unchecked' syntax to override)
Compile: 190.472ms | Execution: 0.000ms | React with ❌ to remove this embed.
Angius
Angius4mo ago
You can't cast it
jcotton42
jcotton424mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ that's only an issue for literals pretty sure uh modix? you showed the result for a split second?
Angius
Angius4mo ago
I saw that too lol
jcotton42
jcotton424mo ago
in any case, in an unchecked context (the default) it's just a reinterpret cast so the underlying bits remain the same
MODiX
MODiX4mo ago
jcotton42
REPL Result: Success
int i = -17;
uint u = (uint)i;
int i2 = (int)u;

Console.WriteLine(i);
Console.WriteLine(u);
Console.WriteLine(i2);
int i = -17;
uint u = (uint)i;
int i2 = (int)u;

Console.WriteLine(i);
Console.WriteLine(u);
Console.WriteLine(i2);
Console Output
-17
4294967279
-17
-17
4294967279
-17
Compile: 356.110ms | Execution: 68.280ms | React with ❌ to remove this embed.
ikalou.
ikalou.4mo ago
Thanks everyone! Yes I tested it on my machine but I wanted to make sure I could rely on it the result wasn't undefined / an implementation detail.
Want results from more Discord servers?
Add your server
More Posts