C
C#10mo 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
MODiX10mo 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
Angius10mo ago
You can't cast it
jcotton42
jcotton4210mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ that's only an issue for literals pretty sure uh modix? you showed the result for a split second?
Angius
Angius10mo ago
I saw that too lol
jcotton42
jcotton4210mo ago
in any case, in an unchecked context (the default) it's just a reinterpret cast so the underlying bits remain the same
MODiX
MODiX10mo 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.OP10mo 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