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.
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));
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With