英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论