Java print four byte hexadecimal number

2019-04-20 15:03发布

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.

4条回答
唯我独甜
2楼-- · 2019-04-20 15:33

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));
}
查看更多
Bombasti
3楼-- · 2019-04-20 15:33

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);
}
查看更多
4楼-- · 2019-04-20 15:38

Here it is for floats:

    System.out.printf("0x%08X", Float.floatToRawIntBits(8.26f));
查看更多
可以哭但决不认输i
5楼-- · 2019-04-20 15:46

Use

String hex = Integer.toHexString(5421).toUpperCase();  // 152D

To get with leading zeroes

String hex = Integer.toHexString(0x10000 | 5421).substring(1).toUpperCase();
查看更多
登录 后发表回答