Java:如何确保经过十六进制到二进制转换后字节数组的大小为2?

huangapple go评论74阅读模式
英文:

Java: How to ensure byte array of size 2 after Hex to binary conversion?

问题

*正在进行的操作*

我有一个十六进制值字符串 `strHexVal`,我正在使用 `DatatypeConverter.parseHexBinary(strHexVal)` 将其赋值给一个字节数组 `hexBytes`。

*我想要的结果*

字节数组 `hexBytes` 应始终具有大小 `2`,即如果转换后 `hexBytes` 的大小为 1我希望在数组中插入 0如果转换后的大小超过 2则抛出错误

有人可以帮我解决这个问题吗

代码

    String strHexVal= "15";
    byte[] hexBytes = DatatypeConverter.parseHexBinary(strHexVal);
    
    **在这部分需要帮助**
    if (hexBytes.length == 1) {
       hexBytes[1] = hexBytes[0];
       hexBytes[0] = 0x00; //这样会有效吗?
    }
    else if (hexBytes.length > 2) {
       抛出错误
    }
英文:

What I am doing:

I have a hex value string strHexVal, which I am assigning to a byte array hexBytes using DatatypeConverter.parseHexBinary(strHexVal)

What I want

The byte array hexBytes should always be of size 2 i.e. if after conversion the size of hexBytes is 1, I would like to insert the array with 0 and if the size after conversion is more than 2, throw an error

Can anyone help me with this?

Code:

String strHexVal= "15";
byte[] hexBytes = DatatypeConverter.parseHexBinary(strHexVal);

**Need help with this part:**
if ( hexBytes length is 1) {
   hexBytes[1] = hexBytes[0]
   hexBytes[0] = 0x00; //will this work???
}
else if (hexBytes.length > 2) {
   throw error
}

答案1

得分: 1

不可以,你不能只是执行 hexBytes[0] = 0x00;,因为一旦创建了Java数组,其大小就是固定的。

你需要创建一个新的 byte[] 数组:

if (hexBytes.length == 1) {
    hexBytes = new byte[] { 0, hexBytes[0] };
}

确保你也要决定在 hexBytes.length 为0时要做什么。如果输入字符串为空,就会出现这种情况。

英文:

No, you can't just do hexBytes[0] = 0x00; because Java arrays have a fixed size once they are created.

You have to create a new byte[]:

if ( hexBytes.length == 1) {
    hexBytes = new byte[] { 0, hexBytes[0] };
}

Make sure you decide what to do if hexBytes.length is 0 as well. This will be the case if the input string is empty.

huangapple
  • 本文由 发表于 2020年4月8日 16:13:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/61096206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定