问题

我必须在java中以字节数组的形式存储一些常量值(UUID),我想知道初始化这些静态数组的最佳方法是什么。这就是我目前正在做的事情,但我觉得必须有一个更好的方法。

private static final byte[] CDRIVES = new byte[] { (byte)0xe0, 0x4f, (byte)0xd0,
    0x20, (byte)0xea, 0x3a, 0x69, 0x10, (byte)0xa2, (byte)0xd8, 0x08, 0x00, 0x2b,
    0x30, 0x30, (byte)0x9d };
private static final byte[] CMYDOCS = new byte[] { (byte)0xba, (byte)0x8a, 0x0d,
    0x45, 0x25, (byte)0xad, (byte)0xd0, 0x11, (byte)0x98, (byte)0xa8, 0x08, 0x00,
    0x36, 0x1b, 0x11, 0x03 };
private static final byte[] IEFRAME = new byte[] { (byte)0x80, 0x53, 0x1c,
    (byte)0x87, (byte)0xa0, 0x42, 0x69, 0x10, (byte)0xa2, (byte)0xea, 0x08,
    0x00, 0x2b, 0x30, 0x30, (byte)0x9d };
...
and so on

有什么我可以使用可能效率较低但看起来更干净的东西吗?例如:

private static final byte[] CDRIVES =
    new byte[] { "0xe04fd020ea3a6910a2d808002b30309d" };

#1 热门回答(90 赞)

使用将hexa字符串转换为byte[]的函数,你可以这样做

byte[] CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");

我建议你使用Dave L在Convert a string representation of a hex dump to a byte array using Java?中定义的函数

我将其插入此处以获得最大可读性:

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

如果你让CDRIVESstaticfinal,性能下降是无关紧要的。


#2 热门回答(43 赞)

byte[] myvar = "Any String you want".getBytes();

#3 热门回答(29 赞)

在Java 6中,有一种方法可以完全满足你的需求:

private static final byte[] CDRIVES = javax.xml.bind.DatatypeConverter.parseHexBinary("e04fd020ea3a6910a2d808002b30309d")

或者你可以使用Google Guava

import com.google.common.io.BaseEncoding;
private static final byte[] CDRIVES = BaseEncoding.base16().lowerCase().decode("E04FD020ea3a6910a2d808002b30309d".toLowerCase());

当你使用小数组时,Guava方法是过度的。但是Guava还有可以解析输入流的版本。处理大十六进制输入时,这是一个很好的功能。


原文链接