views:

1587

answers:

5

Hi,

can you increment a hex value in Java? i.e. "hex value" = "hex value"++

+8  A: 

What do you mean with "hex value"? In what data type is your value stored?

Note that int/short/char/... don't care how your value is represented initially:

int i1 = 0x10;
int i2 = 16;

i1 and i2 will have the exact same content. Java (and most other languages as well) don't care about the notation of your constants/values.

Joachim Sauer
+3  A: 

Yes. All ints are binary anyway, so it doesn't matter how you declare them.

int hex = 0xff;
hex++;  // hex is now 0x100, or 256
int hex2 = 255;
hex2++; // hex2 is now 256, or 0x100
Michael Myers
+5  A: 

It depends how the hex value is stored. If you've got the hex value in a string, convert it to an Integer, increment and convert it back.

int value = Integer.parseInt(hex, 16);
value++;
String incHex = Integer.toHexString(value);
Phil
+6  A: 

Short answer: yes. It's

myHexValue++;

Longer answer: It's likely your 'hex value' is stored as an integer. The business of converting it into a hexadecimal (as opposed to the usual decimal) string is done with

Integer.toHexString( myHexValue )

and from a hex string with

Integer.parseInt( someHexString, 16 );

M.

Martin Cowie
Or String.format("%x", myHexValue);
Michael Myers
A: 

The base of the number is purely a UI issue. Internally an integer is stored as binary. Only when you convert it to human representation do you choose a numeric base. So you're question really boils down to "how to increment an integer?".

Steve Kuo