Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java print four byte hexadecimal number

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.

like image 569
user35443 Avatar asked Feb 03 '13 10:02

user35443


2 Answers

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));
}
like image 125
Hui Zheng Avatar answered Oct 18 '22 14:10

Hui Zheng


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);
}
like image 26
Fix It Until It's Broken Avatar answered Oct 18 '22 16:10

Fix It Until It's Broken