日期:2014-05-20 浏览次数:20891 次
// byte to String byte b = 0x08; int i = ((Byte)b).intValue(); System.out.println(i); String s = Integer.toBinaryString(i); System.out.println(s); // String to byte String s2 = "00001000"; // 按二进制转换s2 byte b2 = Byte.parseByte(s2, 2); System.out.println(b2);
------解决方案--------------------
直接上代码了
刚才测了下,在不打印的情况下,两个方法执行一次用时2.4013782070000002E-6秒
public class Test { public static void main(String[] args) { long start = System.nanoTime(); //不输出结果运行1000000次 for(int i = 0;i < 1e6;i++){ byte[] bys = {0x01,0x02,0x03}; bytesToString(bys); //System.out.println(bytesToString(bys)); byte[] bys2 = stringTobytes("000010000000100100001010"); //for(byte b:bys2) //System.out.println(b); } long end = System.nanoTime(); System.out.println("time:" + (end - start) / 1e9 + "s"); System.out.println("pre time:" + (end - start) / 1e9 / 1e6 + "s"); } private static String bytesToString(byte[] bys){ StringBuffer sb = new StringBuffer(); for(int i = 0;i < bys.length;i++){ String s = String.valueOf(bys[i]); for(int j = 0;j < Byte.SIZE - s.length();j++) sb.append("0"); sb.append(s); } return sb.toString(); } private static byte[] stringTobytes(String str){ byte[] bys = new byte[str.length() / Byte.SIZE]; for(int i = 0;i < bys.length;i++){ String s = str.substring(i * Byte.SIZE,(i + 1) * Byte.SIZE); for(int j = 0;j < s.length();j++){ if(s.charAt(j) == '1') bys[i] |= (1 << (Byte.SIZE - j - 1)); } } return bys; } }