我在做什么:
我有一个十六进制值字符串strHexVal
,我使用DatatypeConverter.parseHexBinary(strHexVal)
将其分配给字节数组hexBytes
我想要什么
字节数组hexBytes
的大小应始终为2
,即如果转换后hexBytes
的大小为1,我想插入为0的数组,如果转换后的大小大于2,则抛出错误
有人可以帮我解决这个问题吗?
代码:
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
}
最佳答案
不,您不能只执行 hexBytes[0] = 0x00;
,因为 Java 数组一旦创建就有固定的大小。
您必须创建一个新的byte[]
:
if ( hexBytes.length == 1) {
hexBytes = new byte[] { 0, hexBytes[0] };
}
确保您决定如果 hexBytes.length
也为 0 时该怎么办。如果输入字符串为空,就会出现这种情况。
关于Java:如何确保十六进制转换为二进制后大小为2的字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61096206/