Java code To convert byte to Hexadecimal

后端 未结 19 2456
我寻月下人不归
我寻月下人不归 2020-11-22 17:26

I have an array of bytes. I want each byte String of that array to be converted to its corresponding hexadecimal values.

Is there any function in Java to convert a b

19条回答
  •  忘了有多久
    2020-11-22 17:44

    Just like some other answers, I recommend to use String.format() and BigInteger. But to interpret the byte array as big-endian binary representation instead of two's-complement binary representation (with signum and incomplete use of possible hex values range) use BigInteger(int signum, byte[] magnitude), not BigInteger(byte[] val).

    For example, for a byte array of length 8 use:

    String.format("%016X", new BigInteger(1,bytes))
    

    Advantages:

    • leading zeros
    • no signum
    • only built-in functions
    • only one line of code

    Disadvantage:

    • there might be more efficient ways to do that

    Example:

    byte[] bytes = new byte[8];
    Random r = new Random();
    System.out.println("big-endian       | two's-complement");
    System.out.println("-----------------|-----------------");
    for (int i = 0; i < 10; i++) {
        r.nextBytes(bytes);
        System.out.print(String.format("%016X", new BigInteger(1,bytes)));
        System.out.print(" | ");
        System.out.print(String.format("%016X", new BigInteger(bytes)));
        System.out.println();
    }
    

    Example output:

    big-endian       | two's-complement
    -----------------|-----------------
    3971B56BC7C80590 | 3971B56BC7C80590
    64D3C133C86CCBDC | 64D3C133C86CCBDC
    B232EFD5BC40FA61 | -4DCD102A43BF059F
    CD350CC7DF7C9731 | -32CAF338208368CF
    82CDC9ECC1BC8EED | -7D3236133E437113
    F438C8C34911A7F5 | -BC7373CB6EE580B
    5E99738BE6ACE798 | 5E99738BE6ACE798
    A565FE5CE43AA8DD | -5A9A01A31BC55723
    032EBA783D2E9A9F | 032EBA783D2E9A9F
    8FDAA07263217ABA | -70255F8D9CDE8546
    

提交回复
热议问题