日期:2014-05-20 浏览次数:20868 次
public class hextostring { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub byte[] b = {(byte) 0xFF ,(byte)0xFA, 0x18 ,0x00 ,0x41 ,0x4E ,0x53 ,0x49 ,(byte)0xFF ,(byte)0xF0}; String s=new String(); try { s=new String(b, "UTF-8"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.printf("%08x ",0); for(int i=0;i<b.length;i++) System.out.printf("%02X ",b[i]); System.out.println(s); } }
------解决方案--------------------
没看清什么要求
------解决方案--------------------
看不得不是很懂..
------解决方案--------------------
准确点说,应该是:如何把字节数组转换成十六进制的整数
public class Convert { /** * 将字节数组编码成十六进制表示的字符串,每个字节用两个十六进制字符表示,不足两位 * 时在左边补0 * @param data 被编码的字节数组 * @param seperator 字节之间的分隔符 * @return 转换后的字符串 */ public static String toHexString(byte[] data, String seperator){ StringBuilder sb = new StringBuilder(data.length * (2 + seperator.length())); int pb = 0; String pre = ""; while(pb < data.length){ byte b = data[pb++]; int h = ((0xF0 & b) >> 4); int l = (0x0F & b); sb.append(pre); if(h < 10){ sb.append((char)('0' + h)); }else{ sb.append((char)('a' + h - 10)); } if(l < 10){ sb.append((char)('0' + l)); }else{ sb.append((char)('a' + l - 10)); } pre = seperator; } return sb.toString(); } /** * 将十六进制字符串表示的字节数据还原成字节数组 * @param text 被还原的字符串 * @return 还原之后的字节数组 */ public static byte[] fromHexString(String text){ if(text == null) return new byte[0]; byte[] result = new byte[text.length() / 2]; text = text.toLowerCase(); int pb = 0; int ps = 0; while(pb < result.length && ps < text.length()){ char ch = text.charAt(ps++); char cl = text.charAt(ps++); int a = 0; int b = 0; if('0' <= ch && ch <= '9'){ a = ch - '0'; }else{ a = ch - 'a' + 10; } if('0' <= cl && cl <= '9'){ b = cl - '0'; }else{ b = cl - 'a' + 10; } result[pb++] = (byte)((a << 4) + b); } return result; } }
------解决方案--------------------
已测试的:
public class strtohex { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String s="import方式可以改变Ecl111,This is a test!"; // String s="12345678901234567"; byte b[]=s.getBytes(); int i,j; for( i=0;i<b.length/16;i++) { System.out.printf("%08x: ",i); for(j=0;j<16;j++) { System.out.printf("%02X ", b[i*16+j]); } String s1=null; try { s1=new String(b,"ISO8859-1"); s1=s1.substring(i*16,i*16+16); s1=new String(s1.getBytes("ISO8859-1"),"GBK"); //linux:UTF-8 } catch (Exception e) { e.printStackTrace(); } System.out.print("; "); System.out.println(s1); } int l=b.length; if (l%16!=0) { System.out.printf("%08x: ",i); for(j=i*16;j<l;j++) System.out.printf("%02X ", b[j]); for(j=0;j<16-l%16;j++) System.out.print("00 "); String s1=null; try { s1=new String(b,"ISO8859-1"); s1=s1.substring(i*16,i*16+l%16); s1=new String(s1.getBytes("ISO8859-1"),"GBK"); //linux:UTF-8 } catch (Exception e) { e.printStackTrace(); } System.out.print("; "); System.out.println(s1); } } }