我想将字符符号从.hex文件转换为字节数组。我正在使用此代码,但结果与我的文件中的符号不同。
我的代码:
public byte[] getResource(int id, Context context) throws IOException {
Resources resources = context.getResources();
InputStream is = resources.openRawResource(id);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] readBuffer = new byte[2 * 1024 * 1024];
byte[] data;
try {
int read;
do {
read = is.read(readBuffer, 0, readBuffer.length);
if (read == -1) {
break;
}
String hex = new String(readBuffer);
data = hexStringToByteArray(hex);
bout.write(data);
// bout.write(readBuffer, 0, read);
} while (true);
return bout.toByteArray();
} finally {
is.close();
}
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
我的.hex文件中的前3行
:020000040800F2 :20000000103C0020650200081502000817020008190200081B0200081D0200080000000056 :200020000000000000000000000000001F020008210200080000000023020008714A00087C
但是当我检查结果数组时,我看到了这个: -16,32,0,0,64,-128,15,31,-17,32,0,0,0,16,60,0,32,101,2,0,8,21 ... < / p>
我的错误在哪里?请告诉我正确的方法!
答案 0 :(得分:1)
首先从文件中读取所有数据并从字符串中删除所有不正确的符号(':'),如@pitfall所说并存储在字符串中然后执行以下操作。
String s="yourStringFromFile";
byte[] b = new BigInteger(s,16).toByteArray();
答案 1 :(得分:0)
您应该从十六进制字符串中删除所有不正确的符号(例如&#39;:&#39;)。
hexStringToByteArray(&#34;:020000040800F&#34;) - &gt; [-16,32,0,0,64,-128,15] hexStringToByteArray(&#34; 020000040800F2&#34;) - &gt; [2,0,0,4,8,0,-14]