站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题16进制字符串转换为字节数组

16进制字符串转换为字节数组

摘要: 16进制字符串转换为字节数组

</td> </tr> <tr> <td width="512" height="35" valign="top" class="ArticleTeitle"> //代码来jive-jdon。
public class HexstringtoByte{
public static final byte[] decodeHex(String hex) {
char [] chars = hex.toCharArray();
for(int i=0;i System.out.print(chars[i]);
}
System.out.println();
byte[] bytes = new byte[chars.length/2];
int byteCount = 0;
for (int i=0; i byte newByte = 0x00;
newByte |= hexCharToByte(chars[i]);
newByte <<= 4;
newByte |= hexCharToByte(chars[i+1]);
bytes[byteCount] = newByte;
byteCount++;
}
return bytes;
}


private static final byte hexCharToByte(char ch) {
switch(ch) {
case '0': return 0x00;
case '1': return 0x01;
case '2': return 0x02;
case '3': return 0x03;
case '4': return 0x04;
case '5': return 0x05;
case '6': return 0x06;
case '7': return 0x07;
case '8': return 0x08;
case '9': return 0x09;
case 'a': return 0x0A;
case 'b': return 0x0B;
case 'c': return 0x0C;
case 'd': return 0x0D;
case 'e': return 0x0E;
case 'f': return 0x0F;
}
return 0x00;
}

public static void main(String args[]){
String s="220c04faf8377f58";
byte a[]=decodeHex(s);
for(int i=0;i System.out.println(a[i]);
}
}


运行结果:
C:\java>java HexstringtoByte

C:\java>java HexstringtoByte
220c04faf8377f58
34
12
4
-6
-8
55
127
88

C:\java></td> <td width="172" valign="top" class="ArticleTeitle">
</td> </tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">


↑返回目录
前一篇: 字节数组转换为16进制字符串
后一篇: 一个日志工具类