java 初始化字节数组,我如何初始化Java的字节数组?

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

解决方案

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

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

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;

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值