在介紹具體方法之前,首先介紹兩個概念:位(bit)和字節(byte)。計算機中以二進制來存儲數據,二進制共有兩個數:0和1。一個0或一個1即為1位。8位即為一個字節,字節為計算機存儲空間的基本計量單位。
一般,一個英文字符或數字占一個字節,一個漢字占2個字節。
在各種語言中,數據類型都占用一定的存儲空間,在Java中,各數據類型占用的空間情況如下:
數據類型 | 字節 | 數據范圍 | |
byte | 1個字節(8位) | -128~127 (-27~27-1) | |
short | 2個字節(16位) | -32768~32767 (-215~215-1) | |
int | 4個字節(32位) | -2147483648~2147483647 (-231~231-1) | |
long | 8個字節(64位) | -9223372036854774808~9223372036854774807 (-263~263-1) | |
float | 4個字節(32位) | 3.402823e+38 ~ 1.401298e-45 | |
double | 8個字節(64位) | 1.797693e+308 ~ 4.9000000e-324 |
Java中數據流的操作很多都是到byte的,但是在許多底層操作中是需要根據一個byte中的bit來做判斷!
下面的代碼根據byte生成bit值!
package com.test;
import java.util.Arrays;
public class T {
/**
* 將byte轉換為一個長度為8的byte數組,數組每個值代表bit
*/
public static byte[] getBooleanArray(byte b) {
byte[] array = new byte[8];
for (int i = 7; i >= 0; i--) {
array[i] = (byte)(b & 1);
b = (byte) (b >> 1);
}
return array;
}
/**
* 把byte轉為字符串的bit
*/
public static String byteToBit(byte b) {
return ""
+ (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
+ (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
+ (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
+ (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
}
public static void main(String[] args) {
byte b = 0x35; // 0011 0101
// 輸出 [0, 0, 1, 1, 0, 1, 0, 1]
System.out.println(Arrays.toString(getBooleanArray(b)));
// 輸出 00110101
System.out.println(byteToBit(b));
// JDK自帶的方法,會忽略前面的 0
System.out.println(Integer.toBinaryString(0x35));
}
}
輸出內容就是各個 bit 位的 0 和 1 值!
根據各個Bit的值,返回byte的代碼:
/**
* 二進制字符串轉byte
*/
public static byte decodeBinaryString(String byteStr) {
int re, len;
if (null == byteStr) {
return 0;
}
len = byteStr.length();
if (len != 4 && len != 8) {
return 0;
}
if (len == 8) {// 8 bit處理
if (byteStr.charAt(0) == '0') {// 正數
re = Integer.parseInt(byteStr, 2);
} else {// 負數
re = Integer.parseInt(byteStr, 2) - 256;
}
} else {// 4 bit處理
re = Integer.parseInt(byteStr, 2);
}
return (byte) re;
}
新聞熱點
疑難解答
圖片精選