Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to two digits hex in Java

Tags:

java

integer

hex

I need to change a integer value into 2-digit hex value in Java.Is there any way for this. Thanks

My biggest number will be 63 and smallest will be 0. I want a leading zero for small values.

like image 893
Salih Erikci Avatar asked Dec 31 '11 17:12

Salih Erikci


People also ask

Which method converts an integer to a hexadecimal string?

toHexString() method in Java converts Integer to hex string. Let's say the following are our integer values. int val1 = 5; int val2 = 7; int val3 = 13; Convert the above int values to hex string.

How do you represent a hex number in Java?

In Java programs, hexadecimal numbers are written by placing 0x before numbers.

What is hexadecimal integer in Java?

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.


2 Answers

String.format("%02X", value); 

If you use X instead of x as suggested by aristar, then you don't need to use .toUpperCase().

like image 169
GabrielOshiro Avatar answered Oct 02 '22 14:10

GabrielOshiro


Integer.toHexString(42); 

Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int)

Note that this may give you more than 2 digits, however! (An Integer is 4 bytes, so you could potentially get back 8 characters.)

Here's a bit of a hack to get your padding, as long as you are absolutely sure that you're only dealing with single-byte values (255 or less):

Integer.toHexString(0x100 | 42).substring(1) 

Many more (and better) solutions at Left padding integers (non-decimal format) with zeros in Java.

like image 26
ziesemer Avatar answered Oct 02 '22 14:10

ziesemer