Converting from decimal to hexadecimal in Java with a leading zero

Converting from decimal to hexadecimal in Java with a leading zero

decimal to hexadecimal

Use the Integer.toHexString method to convert from decimal to hexadecimal in Java.

for (int i = 0; i <= 16; i++) {
  String hex = Integer.toHexString(i);
  System.out.println(hex);
}

The following is the result. Since the return value is of type String, it cannot be filled with leading zeros. (It will be preceded by a single-byte space.)

0
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
10

String.format method to prepend zeros

If you want to convert 1 to a two-digit number by filling it with a leading zero, such as 01 when converting to hexadecimal, use the Integer.valueOf and String.format methods.

for (int i = 0; i <= 16; i++) {
  String hex = String.format("%02x", Integer.valueOf(i));
  System.out.println(hex);
}

As shown below, the one-digit case will be displayed with a leading zero, and the two-digit case will be displayed as is.

00
01
02
03
04
05
06
07
08
09
0a
0b
0c
0d
0e
0f
10

hexadecimal to decimal

Hexadecimal numbers can be easily converted to decimal numbers with the Integer.parseInt method.

String v = "0d"; // 16進数
final Integer n1 = Integer.parseInt(v, 16); // Convert to decimal
final String ch1 = String.format("%02d", n1); // Fill in the front zero

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL