Is there any way to set an int
to a negative value using a hexadecimal literal in C#? I checked the specification on Integer literals but it didn't mention anything.
For example:
int a = -1; // Allowed int b = 0xFFFFFFFF; // Not allowed?
Hexadecimal notation is clearer for my application, and I'd prefer not to use uint
s because I would need to do some extra casting.
From what I understand, you always need to look at the left-most digit to tell the sign. If in hex, then anything from 0-7 is positive and 8-f is negative. Alternatively, you can convert from hex to binary, and if there's a 1 in the left-most digit, then the number is negative.
A hexadecimal integer literal begins with the 0 digit followed by either an x or X, followed by any combination of the digits 0 through 9 and the letters a through f or A through F. The letters A (or a) through F (or f) represent the values 10 through 15, respectively.
A hexadecimal value is int as long as the value fits into int and for larger values it is unsigned , then long , then unsigned long etc. See Section 6.4. 4.1 of the C standard. Just as the accepted answer states.
Use the unchecked keyword.
unchecked { int b = (int)0xFFFFFFFF; }
or even shorter
int b = unchecked((int)0xFFFFFFFF);
i think you can use -0x1
with c#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With