一个象UltraEdit的Ctrl+H(打印16进制)的功能
例如:::
String s = "这是测试examples!" ;
显示为:
00000000h: B2 E2 CA D4 65 78 61 6D 70 6C 65 73 21 ;测试examples!
------解决方案--------------------------------------------------------
- Java code
String s = "测试examples!"; byte[] b = s.getBytes(); for (int i = 0; i < b.length; i++) { System.out.print(Integer.toHexString(b[i] & 0xFF) + " "); } System.out.println();//输出 b2 e2 ca d4 65 78 61 6d 70 6c 65 73 21
------解决方案--------------------------------------------------------
一般就是问个思路,这种只是耗时间排版的工作自己做比较好...
代码如下:
- Java code
/** * 文字转16进制 * * @param s */ public void String2Hex(String s) { byte[] b = s.getBytes(); for (int i = 0; i < b.length; i++) { int row = i / 16;// 行 int col = i % 16;// 列 if (col == 0)// 行头 System.out.print(getLineHead(row)); System.out.print(Integer.toHexString(b[i] & 0xFF) + " "); if (col == 15 || i == b.length - 1)// 行尾 System.out.println(getLineTail(b, row * 16, i % 16 + 1)); } } /** * 得到行头 * * @param k * 当前行数 * @return */ private String getLineHead(int k) { String head = "000000"; head += Integer.toHexString(k) + "0h: "; if (head.length() > 11) return head.substring(head.length() - 9, head.length()); else return head; } /** * 得到行尾 * * @param b * 字节数组 * @param off * 偏移位置 * @param len * 长度 * @return */ private String getLineTail(byte[] b, int off, int len) { StringBuffer tail = new StringBuffer(); for (int i = 0; i < 16 - len; i++) tail.append(" "); tail.append("; " + new String(b, off, len)); return tail.toString(); } //String s = "这是测试examples!"; //String2Hex(s); //输出: //00000000h: d5 e2 ca c7 b2 e2 ca d4 65 78 61 6d 70 6c 65 73 ; 这是测试examples //00000010h: 21 ; !
------解决方案--------------------------------------------------------
SORRY,得到行头的方法有点问题,应该如下:(head.length() - 9 应改为head.length() - 11)
- Java code
/** * 得到行头 * * @param k * 当前行数 * @return */ private String getLineHead(int k) { String head = "000000"; head += Integer.toHexString(k) + "0h: "; if (head.length() > 11) return head.substring(head.length() - 11, head.length()); else return head; }
------解决方案--------------------------------------------------------