获取一个 Byte 的各个 Bit 值

转载自   获取一个 Byte 的各个 Bit 值

1. bit:位
    一个二进制数据0或1,是1bit;
2. byte:字节
    存储空间的基本计量单位,如:MySQL中定义 VARCHAR(45)  即是指 45个字节;
    1 byte = 8 bit
3. 一个英文字符占一个字节;
    1 字母 = 1 byte = 8 bit
4. 一个汉字占2个字节;
    1 汉字 = 2 byte = 16 bit
byte:一个字节(8位)(-128~127)(-2的7次方到2的7次方-1)
short:两个字节(16位)(-32768~32767)(-2的15次方到2的15次方-1)
int:四个字节(32位)(一个字长)(-2147483648~2147483647)(-2的31次方到2的31次方-1)
long:八个字节(64位)(-9223372036854774808~9223372036854774807)(-2的63次方到2的63次方-1)
float:四个字节(32位)(3.402823e+38 ~ 1.401298e-45)(e+38是乘以10的38次方,e-45是乘以10的负45次方)
double:八个字节(64位)(1.797693e+308~ 4.9000000e-324

 

Java中数据流的操作很多都是到byte的,但是在许多底层操作中是需要根据一个byte中的bit来做判断!

Java中要根据byte获得bit就要进行一些位操作,不过为了使用我直接给出解决方案,至于位操作的一些内容,回头再说!

  1. package com.test;  
  2. import java.util.Arrays;  
  3. public class T {  
  4.     /** 
  5.      * 将byte转换为一个长度为8的byte数组,数组每个值代表bit 
  6.      */  
  7.     public static byte[] getBooleanArray(byte b) {  
  8.         byte[] array = new byte[8];  
  9.         for (int i = 7; i >= 0; i--) {  
  10.             array[i] = (byte)(b & 1);  
  11.             b = (byte) (b >> 1);  
  12.         }  
  13.         return array;  
  14.     }  
  15.     /** 
  16.      * 把byte转为字符串的bit 
  17.      */  
  18.     public static String byteToBit(byte b) {  
  19.         return ""  
  20.                 + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)  
  21.                 + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)  
  22.                 + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)  
  23.                 + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);  
  24.     }  
  25.     public static void main(String[] args) {  
  26.         byte b = 0x35// 0011 0101  
  27.         // 输出 [0, 0, 1, 1, 0, 1, 0, 1]  
  28.         System.out.println(Arrays.toString(getBooleanArray(b)));  
  29.         // 输出 00110101  
  30.         System.out.println(byteToBit(b));  
  31.         // JDK自带的方法,会忽略前面的 0  
  32.         System.out.println(Integer.toBinaryString(0x35));  
  33.     }  
  34. }  

 输出内容就是各个 bit 位的 0 和 1 值!

 

根据各个Bit的值,返回byte的代码:

  1. /** 
  2.  * 二进制字符串转byte 
  3.  */  
  4. public static byte decodeBinaryString(String byteStr) {  
  5.     int re, len;  
  6.     if (null == byteStr) {  
  7.         return 0;  
  8.     }  
  9.     len = byteStr.length();  
  10.     if (len != 4 && len != 8) {  
  11.         return 0;  
  12.     }  
  13.     if (len == 8) {// 8 bit处理  
  14.         if (byteStr.charAt(0) == '0') {// 正数  
  15.             re = Integer.parseInt(byteStr, 2);  
  16.         } else {// 负数  
  17.             re = Integer.parseInt(byteStr, 2) - 256;  
  18.         }  
  19.     } else {// 4 bit处理  
  20.         re = Integer.parseInt(byteStr, 2);  
  21.     }  
  22.     return (byte) re;  
  23. }  

 


猜你喜欢

转载自blog.csdn.net/moakun/article/details/80712604