Java print four byte hexadecimal number
37,787
Solution 1
Here are two functions, one for integer, one for float.
public static String hex(int n) {
// call toUpperCase() if that's required
return String.format("0x%8s", Integer.toHexString(n)).replace(' ', '0');
}
public static String hex(float f) {
// change the float to raw integer bits(according to the OP's requirement)
return hex(Float.floatToRawIntBits(f));
}
Solution 2
For Integers, there's an even easier way. Use capital 'X' if you want the alpha part of the hex number to be upper case, otherwise use 'x' for lowercase. The '0' in the formatter means keep leading zeroes.
public static String hex(int n)
{
return String.format("0x%04X", n);
}
Solution 3
Here it is for floats:
System.out.printf("0x%08X", Float.floatToRawIntBits(8.26f));
Solution 4
Use
String hex = Integer.toHexString(5421).toUpperCase(); // 152D
To get with leading zeroes
String hex = Integer.toHexString(0x10000 | 5421).substring(1).toUpperCase();
Author by
user35443
Updated on July 09, 2022Comments
-
user35443 almost 2 years
I have a small problem. I have numbers like 5421, -1 and 1. I need to print them in four bytes, like:
5421 -> 0x0000152D -1 -> 0xFFFFFFFF 1 -> 0x00000001
Also, I have floating point numbers like 1.2, 58.654:
8.25f -> 0x41040000 8.26 -> 0x410428f6 0.7 -> 0x3f333333
I need convert both types of numbers into their hexadecimal version, but they must be exactly four bytes long (four pairs of hexadecimal digits).
Does anybody know how is this possible in Java? Please help.
-
Kevin Bowersox about 11 years
System.out.println(Integer.toHexString(5421));
--> 152d -
Sri Harsha Chilakapati about 11 yearsThe java doc says that it gives without leading zeroes.
-
Hui Zheng about 11 years@SriHarshaChilakapati but the OP requires the leading zeros.
-
Kevin Bowersox about 11 yearsNice answer, gives the leading 0's as requested.
-
Hui Zheng about 11 years@SriHarshaChilakapati Your updated answer still has bug, try replacing 5421 with 99999999.
-
Hui Zheng about 11 years@user35443 floats are different, can you add samples for floats in your question?
-
Victor Zamanian over 8 yearsThe
hex(int)
method could also have a format of"%#08x"
, to print the "0x" and leading zeros for you.