简体   繁体   中英

Increment a Hex value (JAVA)

can you increment a hex value in Java? ie "hex value" = "hex value"++

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);

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.

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.

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

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?".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM