byte和bite之间的转换

来源:互联网 发布:自考网络助学平台 编辑:程序博客网 时间:2024/06/06 19:40
Java代码  收藏代码
  1. // 返回无符号的2进制表示 1110011  
  2. String hex = Integer.toBinaryString(115);  
  3. System.out.println(hex);  
  4. // 返回2进制的字符串1110011对应的值 115  
  5. System.out.println(Integer.valueOf("1110011"2));  
  6.   
  7. // 16进制值转换成二进制  
  8. System.out.println(Long.parseLong("49"16));  
  9. System.out.println(Long.parseLong("2F"16));  

 

Java代码  收藏代码
  1. /** 
  2.  * Byte转Bit 
  3.  */  
  4. public static String byteToBit(byte b) {  
  5.     return "" +(byte)((b >> 7) & 0x1) +   
  6.     (byte)((b >> 6) & 0x1) +   
  7.     (byte)((b >> 5) & 0x1) +   
  8.     (byte)((b >> 4) & 0x1) +   
  9.     (byte)((b >> 3) & 0x1) +   
  10.     (byte)((b >> 2) & 0x1) +   
  11.     (byte)((b >> 1) & 0x1) +   
  12.     (byte)((b >> 0) & 0x1);  
  13. }  
  14.   
  15. /** 
  16.  * Bit转Byte 
  17.  */  
  18. public static byte BitToByte(String byteStr) {  
  19.     int re, len;  
  20.     if (null == byteStr) {  
  21.         return 0;  
  22.     }  
  23.     len = byteStr.length();  
  24.     if (len != 4 && len != 8) {  
  25.         return 0;  
  26.     }  
  27.     if (len == 8) {// 8 bit处理  
  28.         if (byteStr.charAt(0) == '0') {// 正数  
  29.             re = Integer.parseInt(byteStr, 2);  
  30.         } else {// 负数  
  31.             re = Integer.parseInt(byteStr, 2) - 256;  
  32.         }  
  33.     } else {//4 bit处理  
  34.         re = Integer.parseInt(byteStr, 2);  
  35.     }  
  36.     return (byte) re;  
  37. }  
0 0
原创粉丝点击