我需要在字节数组的开头添加字符串“00”或字节0x00。我尝试用for循环来实现,但当我将其转换为十六进制时,它不会显示在最前面。
我需要在字节数组的开头添加字符串“00”或字节0x00。我尝试用for循环来实现,但当我将其转换为十六进制时,它不会显示在最前面。
当转换为字节时,字符串“00”与数字0x00是不同的。你试图将什么数据类型附加到你的字节数组中?假设它是字符串“00”的字节表示形式,请尝试以下方法:
bytes[] orig = <your byte array>;
String prepend = "00";
bytes[] prependBytes = prepend.getBytes();
bytes[] output = new Bytes[prependBytes.length + orig.length];
for(i=0;i<prependBytes.length;i++){
output[i] = prependBytes[i];
}
for(i=prependBytes.length;i<(orig.length+prepend.lenth);i++){
output[i] = orig[i];
}
byte[] prependBytes = new byte[]{0,0};
您提到正在将字节数组转换为十六进制,这可能会截断前导零。为了测试这一点,请尝试在以下内容前面添加并转换为十六进制,看看是否有不同的输出:
byte[] prependBytes = new byte[]{1,1};
output[i] = orig[i];
不应该是 output[i] = orig[i-prependBytes.length];
吗?这样才不会超出索引范围。 - OscarVanLbyte[] orig = <your byte array>;
byte[] prependBytes = new byte[]{0,0};
byte[] output = new byte[prependBytes.length + orig.length];
for(int i=0;i<prependBytes.length;i++){
output[i] = prependBytes[i];
}
for(int i=prependBytes.length;i<(prependBytes.length+orig.length);i++){
output[i] = orig[i-prependBytes.length];
}
- djp3