Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting ints to negative values using hexadecimal literals in C#

Tags:

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 uints because I would need to do some extra casting.

like image 804
sourcenouveau Avatar asked Jan 22 '10 21:01

sourcenouveau


People also ask

How do you represent a negative value in hexadecimal?

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.

What are hexadecimal literals?

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.

Is hex signed or unsigned?

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.


2 Answers

Use the unchecked keyword.

unchecked {    int b = (int)0xFFFFFFFF;     } 

or even shorter

int b = unchecked((int)0xFFFFFFFF); 
like image 173
Mikael Svenson Avatar answered Oct 02 '22 11:10

Mikael Svenson


i think you can use -0x1 with c#

like image 29
jspcal Avatar answered Oct 02 '22 11:10

jspcal