把從SD卡裡取出來的字符串“0x03 0x04 0x05"轉為(byte)0x03 (byte)0x03
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
if(hexString.indexOf("0X")>=0) hexString=hexString.replace("0X", "");
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
byte[] by = hexStringToBytes("0x030x040x05");
byte[] by2 = new byte[]{(byte) 0x03,(byte) 0x04,(byte) 0x05};
//這兩個by和by2是一致的
}