Java: 如何保证十六进制转二进制后字节数组大小为2?
Java: How to ensure byte array of size 2 after Hex to binary conversion?
我在做什么:
我有一个十六进制值字符串 strHexVal
,我正在使用 DatatypeConverter.parseHexBinary(strHexVal)
将其分配给字节数组 hexBytes
我想要的
字节数组 hexBytes
的大小应始终为 2
即,如果转换后 hexBytes
的大小为 1,我想插入带有 0 的数组,如果转换后的size大于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,请确保您决定要做什么。如果输入字符串为空,就会出现这种情况。
我在做什么:
我有一个十六进制值字符串 strHexVal
,我正在使用 DatatypeConverter.parseHexBinary(strHexVal)
hexBytes
我想要的
字节数组 hexBytes
的大小应始终为 2
即,如果转换后 hexBytes
的大小为 1,我想插入带有 0 的数组,如果转换后的size大于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,请确保您决定要做什么。如果输入字符串为空,就会出现这种情况。