views:

91

answers:

5

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.

+1  A: 

i think you can use -0x1 with c#

jspcal
Yes, this is valid syntax, but having to do the negation in my head to figure out what the real value is is a bit tedious.
emddudley
A: 

You can use the "Convert" class:

string hex = "FF7F";
int myInt = Convert.ToInt32(hex, 16);
A: 

This Dim i As Integer = &HFFFFFFFF works in VB.

dbasnett
+5  A: 

Use the unchecked keyword.

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

or even shorter

int b = unchecked((int)0xFFFFFFFF);
Mikael Svenson
A: 

You have to cast it and put it in an unchecked context.

unchecked {
    int i = (int)0xFFFFFFFF;
}
Jason