我有一个字节数组。 我希望将该数组的每个字节String转换为相应的十六进制值。

Java中是否有将字节数组转换为十六进制的函数?


当前回答

如果你使用奇妙仙子,那么有:

package com.google.crypto.tink.subtle;

public final class Hex {
  public static String encode(final byte[] bytes) { ... }
  public static byte[] decode(String hex) { ... }
}

所以像这样的东西应该是有用的:

import com.google.crypto.tink.subtle.Hex;

byte[] bytes = {-1, 0, 1, 2, 3 };
String enc = Hex.encode(bytes);
byte[] dec = Hex.decode(enc)

其他回答

最好的解决方案是这样的一句话:

String hex=DatatypeConverter.printHexBinary(byte[] b);

正如这里提到的

我不知道你说的字节字符串到底是什么意思,但这里有一些从字节到字符串的转换,反之亦然,当然官方文档上有更多

Integer intValue = 149;

对应的字节值为:

Byte byteValue = intValue.byteValue(); // this will convert the rightmost byte of the intValue to byte, because Byte is an 8 bit object and Integer is at least 16 bit, and it will give you a signed number in this case -107

从Byte变量中返回整数值:

Integer anInt = byteValue.intValue(); // This will convert the byteValue variable to a signed Integer

从字节和整数到十六进制字符串: 我是这样做的:

Integer anInt = 149
Byte aByte = anInt.byteValue();

String hexFromInt = "".format("0x%x", anInt); // This will output 0x95
String hexFromByte = "".format("0x%x", aByte); // This will output 0x95

将字节数组转换为十六进制字符串: 据我所知,没有一个简单的函数可以将某个对象的数组中的所有元素转换为另一个对象的元素,所以你必须自己做。您可以使用以下函数:

从byte[]到String:

    public static String byteArrayToHexString(byte[] byteArray){
        String hexString = "";

        for(int i = 0; i < byteArray.length; i++){
            String thisByte = "".format("%x", byteArray[i]);
            hexString += thisByte;
        }

        return hexString;
    }

从十六进制字符串到字节[]:

public static byte[] hexStringToByteArray(String hexString){
    byte[] bytes = new byte[hexString.length() / 2];

    for(int i = 0; i < hexString.length(); i += 2){
        String sub = hexString.substring(i, i + 2);
        Integer intVal = Integer.parseInt(sub, 16);
        bytes[i / 2] = intVal.byteValue();
        String hex = "".format("0x%x", bytes[i / 2]);
    }

    return bytes;
}  

现在已经太迟了,但我希望这能帮助到其他人;)

使用BigInteger将byte[]转换为十六进制字符串的简单方法:

import java.math.BigInteger;

byte[] bytes = new byte[] {(byte)255, 10, 20, 30};
String hex = new BigInteger(1, bytes).toString(16);
System.out.println(hex); // ff0a141e

它是如何工作的?

内置的系统类java.math.BigInteger类(java.math.BigInteger)兼容二进制和十六进制数据:

它有一个构造函数BigInteger(signum=1, byte[])通过byte[]创建一个大整数(设置它的第一个参数signum=1以正确处理负字节) 使用BigInteger.toString(16)将大整数转换为十六进制字符串 要解析十六进制数,请使用new BigInteger("ffa74b", 16) -不能正确处理前导零

如果你想在十六进制结果中有前导零,检查它的大小,并在必要时添加缺少的零:

if (hex.length() % 2 == 1)
    hex = "0" + hex;

笔记

使用new BigInteger(1, bytes),而不是new BigInteger(bytes),因为Java“被设计破坏了”,字节数据类型不包含字节,而是有符号的小整数[-128…127]。如果第一个字节是负的,BigInteger假设您传递了一个负的大整数。只需传递1作为第一个参数(signum=1)。

从十六进制转换回字节[]是棘手的:有时前导零进入产生的输出,它应该像这样被清除:

byte[] bytes = new BigInteger("ffa74b", 16).toByteArray();
if (bytes[0] == 0) {
    byte[] newBytes = new byte[bytes.length - 1];
    System.arraycopy(bytes, 1, newBytes, 0, newBytes.length);
    bytes = newBytes;
}

最后一个提示是如果字节[]有几个前导零,它们将丢失。

Java 17:引入Java .util. hexformat

Java 17提供了一个实用程序,可以将字节数组和数字转换为对应的十六进制数。假设我们有一个“Hello World”的MD5摘要作为一个字节数组:

var md5 = MessageDigest.getInstance("md5");
md5.update("Hello world".getBytes(UTF_8));

var digest = md5.digest();

现在我们可以使用HexFormat.of().formatHex(byte[])方法将给定的byte[]转换为它的十六进制形式:

jshell> HexFormat.of().formatHex(digest)
$7 ==> "3e25960a79dbc69b674cd4ec67a72c62"

withUpperCase()方法返回前面输出的大写版本:

jshell> HexFormat.of().withUpperCase().formatHex(digest)
$8 ==> "3E25960A79DBC69B674CD4EC67A72C62"

其他人已经报道了一般情况。但是如果你有一个已知形式的字节数组,例如MAC地址,那么你可以:

byte[] mac = { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 };

String str = String.format("%02X:%02X:%02X:%02X:%02X:%02X",
                           mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);