16进制转换
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1. **
2. * 将指定byte数组以16进制的形式打印到控
制台
3. * @param hint String
4. * @param b byte[]
5. * @return void
6. */
7. public static void printHexString(String hint,
byte[] b) {
8. System.out.print(hint);
9. for (int i = 0; i < b.length; i++) {
10. String hex = Integer.toHexString(b[i] &
0xFF);
11. if (hex.length() == 1) {
12. hex = '0' + hex;
13. }
14. System.out.print(hex.toUpperCase() +
" ");
15. }
16. System.out.println("");
17. }
18. /**
19. *
20. * @param b byte[]
21. * @return String
22. */
23. public static String Bytes2HexString(byte[] b)
{
24. String ret = "";
25. for (int i = 0; i < b.length; i++) {
26. String hex = Integer.toHexString(b[i] &
0xFF);
27. if (hex.length() == 1) {
28. hex = '0' + hex;
29. }
30. ret += hex.toUpperCase();
31. }
32. return ret;
33. }
34. /**
35. * 将两个ASCII字符合成一个字节;
36. * 如:"EF"--> 0xEF
37. * @param src0 byte
38. * @param src1 byte
39. * @return byte
40. */
41. public static byte uniteBytes(byte src0, byte
src1) {
42. byte _b0 = Byte.decode("0x" + new
String(new byte[]{src0})).byteValue();
43. _b0 = (byte)(_b0 << 4);
44. byte _b1 = Byte.decode("0x" + new
String(new byte[]{src1})).byteValue();
45. byte ret = (byte)(_b0 ^ _b1);
46. return ret;
47. }
48. /**
49. * 将指定字符串src,以每两个字符分割转
换为16进制形式
50. * 如:"2B44EFD9" --> byte[]{0x2B, 0x44,
0xEF, 0xD9}
51. * @param src String
52. * @return byte[]
53. */
54. public static byte[] HexString2Bytes(String
src){
55. byte[] ret = new byte[8];
56. byte[] tmp = src.getBytes();
57. for(int i=0; i<8; i++){
58. ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);
59. }
60. return ret;
61. }
toHexString
public static String toHexString(int i)以十六进制的无符号整数形式返回一个整数参数的字符串表示形式。
如果参数为负,那么无符号整数值为参数加上232;否则等于该参数。将该值转换为十六进制(基数16)的无前导0 的ASCII 数字字符串。如果无符号数的大小值为零,则用一个零字符'0' ('\u0030') 表示它;否则,无符号数大小的表示形式中的第一个字符将不是零字符。用以下字符作为十六进制数字:0123456789abcdef
这些字符的范围是从'\u0030' 到'\u0039' 和从'\u0061' 到'\u0066'。如果希望得到大写字母,可以在结果上调用String.toUpperCase() 方法:
Integer.toHexString(n).toUpperCase()
参数:
i - 要转换成字符串的整数。
返回:
用十六进制(基数16)参数表示的无符号整数值的字符串表示形式。
// 转化字符串为十六进制编码
public static String toHexString(String s)
{
String str="";
for (int i=0;i { int ch = (int)s.charAt(i); String s4 = Integer.toHexString(ch); str = str + s4; } return str; } // 转化十六进制编码为字符串 public static String toStringHex(String s) { byte[] baKeyword = new byte[s.length()/2]; for(int i = 0; i < baKeyword.length; i++) {