Sevas
Sevas

Reputation: 4273

Converting between decimal and hexadecimal in Java

Let's say I have a byte value of 0x12 (decimal 18). I need to convert this into decimal 12. Here's how I do it:

byte hex = 0x12;
byte dec = Byte.parseByte(String.format("%2x", hex));
System.out.println(dec); // 12

Is there a better way of doing this (for example without using strings and parsing)?

Upvotes: 0

Views: 1760

Answers (3)

John Dvorak
John Dvorak

Reputation: 27277

If you want to iterpret a Binary coded decimal and convert to binary, you can convert to a hexadecimal string and interpret as a decimal string. Your method is a perfectly valid way to do it (be careful, though, that bytes are signed in Java.

Read up on Binary Coded Decimals here: http://en.wikipedia.org/wiki/Binary-coded_decimal

If you want to avoid string conversion, you could separate each nibble (four bytes) and multiply by the correct value:

byte hex = 0x12;

if( hex&15 > 9 || hex>>>4 > 9)
 throw new NumberFormatException(); //check for valid input

byte dec = (byte)((hex & 15) + 10*(hex>>>4 & 15));

If your input is wider than a byte, this method gets out of hand easily as you need to handle each nibble separately.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838026

Try this:

byte dec = (byte)(hex / 16 * 10 + hex % 16);

Note that it assumes that the original input is a valid BCD encoding.

Upvotes: 2

Ravi K
Ravi K

Reputation: 1016

Hex to Decimal - Integer.parseInt(str,16)

Decimal to Hex - Integer.toHexString(195012)

Upvotes: 0

Related Questions