[英]Java: How to ensure byte array of size 2 after Hex to binary conversion?
What I am doing :我在做什么:
I have a hex value string strHexVal
, which I am assigning to a byte array hexBytes
using DatatypeConverter.parseHexBinary(strHexVal)
我有一个十六进制值字符串
strHexVal
,我使用DatatypeConverter.parseHexBinary(strHexVal)
将其分配给字节数组hexBytes
What I want我想要的是
The byte array hexBytes
should always be of size 2
ie 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字节数组
hexBytes
的大小应始终为2
,即如果转换后hexBytes
的大小为 1,我想用 0 插入数组,如果转换后的大小大于 2,则抛出错误
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
}
No, you can't just do hexBytes[0] = 0x00;
不,你不能只做
hexBytes[0] = 0x00;
because Java arrays have a fixed size once they are created.因为 Java arrays 在创建后具有固定大小。
You have to create a new byte[]
:您必须创建一个新的
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.如果
hexBytes.length
也为 0,请确保您决定要做什么。 This will be the case if the input string is empty.如果输入字符串为空,就会出现这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.