如何在 Java 中初始化字节数组? [英] How do I initialize a byte array in Java?

查看:37
本文介绍了如何在 Java 中初始化字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to store some constant values (UUIDs) in byte array form in java, and I'm wondering what the best way to initialize those static arrays would be. This is how I'm currently doing it, but I feel like there must be a better way.

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

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

Is there anything I could use that may be less efficient, but would look cleaner? for example:

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

推荐答案

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

Using a function converting an hexa string to byte[], you could do

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

我建议您使用 Dave L 在 使用 Java 将十六进制转储的字符串表示形式转换为字节数组?

I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?

我在这里插入它是为了最大程度的可读性:

I insert it here for maximum readability :

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;
}

如果让 CDRIVES staticfinal ,性能下降是无关紧要的.

If you let CDRIVES static and final, the performance drop is irrelevant.

这篇关于如何在 Java 中初始化字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆