我有一个字节数组充满十六进制数字和打印它的简单方式是相当没有意义的,因为有许多不可打印的元素。我需要的是精确的十六进制形式:3a5f771c


当前回答

为了完整起见,一个番石榴解决方案:

import com.google.common.io.BaseEncoding;
...
byte[] bytes = "Hello world".getBytes(StandardCharsets.UTF_8);
final String hex = BaseEncoding.base16().lowerCase().encode(bytes);

现在十六进制是“48656c6c6f20776f726c64”。

其他回答

好的,有很多方法可以做到这一点,但如果你决定使用一个库,我建议在你的项目中看看是否已经在一个库中实现了一些东西,而这个库已经是你项目的一部分,然后再添加一个新的库来做到这一点。例如,如果你还没有

org.apache.commons.codec.binary.Hex

也许你有…

org.apache.xerces.impl.dv.util.HexBin

Java 17最终包含HexFormat类,所以你可以简单地做:

HexFormat.of().formatHex(bytes);

它支持配置为小写/大写,分隔符,前缀,后缀等。

最简单的解决方案,没有外部库,没有数字常量:

public static String byteArrayToHex(byte[] a) {
   StringBuilder sb = new StringBuilder(a.length * 2);
   for(byte b: a)
      sb.append(String.format("%02x", b));
   return sb.toString();
}

在这一页上找不到任何解决方案吗

使用循环 使用javax.xml.bind.DatatypeConverter,它编译良好,但经常在运行时抛出java.lang.NoClassDefFoundError。

这里有一个解决方案,它没有上面的缺陷(不保证我的没有其他缺陷)

import java.math.BigInteger;

import static java.lang.System.out;
public final class App2 {
    // | proposed solution.
    public static String encode(byte[] bytes) {          
        final int length = bytes.length;

        // | BigInteger constructor throws if it is given an empty array.
        if (length == 0) {
            return "00";
        }

        final int evenLength = (int)(2 * Math.ceil(length / 2.0));
        final String format = "%0" + evenLength + "x";         
        final String result = String.format (format, new BigInteger(bytes));

        return result;
    }

    public static void main(String[] args) throws Exception {
        // 00
        out.println(encode(new byte[] {})); 

        // 01
        out.println(encode(new byte[] {1})); 

        //203040
        out.println(encode(new byte[] {0x20, 0x30, 0x40})); 

        // 416c6c20796f75722062617365206172652062656c6f6e6720746f2075732e
        out.println(encode("All your base are belong to us.".getBytes()));
    }
}   

我不能在62个操作码下得到这个,但如果你可以在第一个字节小于0x10的情况下没有0填充,那么下面的解决方案只使用23个操作码。真正展示了“容易实现自己”的解决方案,如“如果字符串长度为奇数,则填充为零”,如果本机实现还不可用(或者在本例中,如果BigInteger在toString中有一个以零作为前缀的选项),则可能会非常昂贵。

public static String encode(byte[] bytes) {          
    final int length = bytes.length;

    // | BigInteger constructor throws if it is given an empty array.
    if (length == 0) {
        return "00";
    }

    return new BigInteger(bytes).toString(16);
}

如果你想让它更具可读性,并将字节彼此分开,你可以在Java 17+中使用以下代码:

byte[] yourByteArray = { -128, 0, 127 };
String hexString = new String(HexFormat.ofDelimiter(" ").formatHex(yourByteArray));
// 80 00 7f