Reputation: 327
I want to convert chars symbols from .hex file to byte array. I am using this code but the result is not the same symbol from my file.
My code:
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;
}
First 3 lines from my .hex file
:020000040800F2 :20000000103C0020650200081502000817020008190200081B0200081D0200080000000056 :200020000000000000000000000000001F020008210200080000000023020008714A00087C
But when I check resulting array, I see this: -16, 32, 0, 0, 64, -128, 15, 31, -17, 32, 0, 0, 0, 16, 60, 0, 32, 101, 2, 0, 8, 21...
Where is my mistake? Show me right way please!
Upvotes: 0
Views: 696
Reputation: 1917
First read all data from file and remove all incorrect symbols such(':') from string as @pitfall says and store in string then do following thing.
String s="yourStringFromFile";
byte[] b = new BigInteger(s,16).toByteArray();
Upvotes: 3
Reputation: 186
You should remove all incorrect symbols (such ':') from hex string.
hexStringToByteArray(":020000040800F") -> [-16, 32, 0, 0, 64, -128, 15] hexStringToByteArray("020000040800F2") -> [2, 0, 0, 4, 8, 0, -14]
Upvotes: 1