如何在Java中将字节数组转换为十六进制格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19450452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:17:09  来源:igfitidea点击:

How to convert byte array to hex format in Java

javaformathexbytearraystringbuilder

提问by James Meade

I know that you can use printfand also use StringBuilder.append(String.format("%x", byte))to convert values to HEX values and display them on the console. But I want to be able to actually format the byte array so that each byte is displayed as HEX instead of decimal.

我知道您可以使用printf并且还可以StringBuilder.append(String.format("%x", byte))用于将值转换为 HEX 值并在控制台上显示它们。但我希望能够实际格式化字节数组,以便每个字节显示为十六进制而不是十进制。

Here is a section of my code that I have already that does the first two ways that I stated:

这是我的代码的一部分,我已经做了我所说的前两种方式:

if(bytes > 0)
    {
        byteArray = new byte[bytes]; // Set up array to receive these values.

        for(int i=0; i<bytes; i++)
        {
            byteString = hexSubString(hexString, offSet, CHARSPERBYTE, false); // Isolate digits for a single byte.
            Log.d("HEXSTRING", byteString);

            if(byteString.length() > 0)
            {
                byteArray[i] = (byte)Integer.parseInt(byteString, 16); // Parse value into binary data array.
            }
            else
            {
                System.out.println("String is empty!");
            }

            offSet += CHARSPERBYTE; // Set up for next word hex.    
        }

        StringBuilder sb = new StringBuilder();
        for(byte b : byteArray)
        {
            sb.append(String.format("%x", b));
        }

        byte subSystem = byteArray[0];
        byte highLevel = byteArray[1];
        byte lowLevel = byteArray[2];

        System.out.println("Byte array size: " + byteArray.length);
        System.out.printf("Byte 1: " + "%x", subSystem);
        System.out.printf("Byte 2: " + "%x", highLevel);
        System.out.println("Byte 3: " + lowLevel);
        System.out.println("Byte array value: " + Arrays.toString(byteArray));
        System.out.println("Byte array values as HEX: " + sb.toString());
    }
    else
    {
        byteArray = new byte[0]; // No hex data.

        //throw new HexException();
    }

    return byteArray;

The string that was split up into the byte array was:

拆分为字节数组的字符串是:

"1E2021345A2B"

But displays it as decimal on the console as:

但在控制台上将其显示为十进制:

"303233529043"

Could anyone please help me on how to get the actual values to be in hex and be displayed in that way naturally. Thank you in advance.

任何人都可以帮助我如何将实际值以十六进制显示并以这种方式自然显示。先感谢您。

回答by Tamas

The way I do it:

我这样做的方式:

  private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
      'B', 'C', 'D', 'E', 'F' };

  public static String toHexString(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for (int j = 0; j < bytes.length; j++) {
      v = bytes[j] & 0xFF;
      hexChars[j * 2] = HEX_CHARS[v >>> 4];
      hexChars[j * 2 + 1] = HEX_CHARS[v & 0x0F];
    }
    return new String(hexChars);
  }

回答by Paul Vargas

You can use the String javax.xml.bind.DatatypeConverter.printHexBinary(byte[]). e.g.:

您可以使用String javax.xml.bind.DatatypeConverter.printHexBinary(byte[]). 例如:

public static void main(String[] args) {
    byte[] array = new byte[] { 127, 15, 0 };
    String hex = DatatypeConverter.printHexBinary(array);
    System.out.println(hex); // prints "7F0F00"
}

回答by VGR

String.formatactually makes use of the java.util.Formatter class. Instead of using the String.format convenience method, use a Formatter directly:

String.format实际上使用了 java.util.Formatter 类。不使用 String.format 便捷方法,而是直接使用 Formatter:

Formatter formatter = new Formatter();
for (byte b : bytes) {
    formatter.format("%02x", b);
}
String hex = formatter.toString();

回答by Dharmesh Gohil

Try this

尝试这个

byte[] raw = some_bytes;
javax.xml.bind.DatatypeConverter.printHexBinary(raw)