当前位置:K88软件开发文章中心编程语言JavaJava01 → 文章内容

Java中获取一个Byte 的各个Bit的值

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2019-1-3 0:09:28

:2012-12-20 19:38:38

在介绍具体方法之前,首先介绍两个概念:位(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;
}


Java中获取一个Byte 的各个Bit的值