第1个回答 2016-05-04
string hexString= "1002010001";
byte[] data = string2Byte(hexString);
ByteBuffer buffer=ByteBuffer.allocate(5);
buffer.put(data);
buffer.flip();
File file = new File("d:/1.dat");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(buffer.array());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
public static byte[] string2Byte(String hexString) {
hexString = hexString.toUpperCase();
char[] chars = hexString.toCharArray();
int len = chars.length >> 1;
byte[] bytes = new byte[len];
for (int i = 0; i != len; i++) {
int position = i << 1;
int high;
int low;
if (chars[position] < 'A') {
high = chars[position] - 0x30;
} else if (chars[position] > 'Z') {
high = chars[position] - 0x57;
} else {
high = chars[position] - 0x37;
}
if (chars[position + 1] < 'A') {
low = chars[position + 1] - 0x30;
} else if (chars[position + 1] > 'Z') {
low = chars[position + 1] - 0x57;
} else {
low = chars[position + 1] - 0x37;
}
high = high << 4;
bytes[i] = (byte) (high + low);
}
return bytes;
}