将具有位的数组转换为一个字节

时间:2015-12-30 03:42:24

标签: java

我试图将8位转换为一个字节。表示位的方式是使用仅包含1或0的字节对象。

如果我有一个带有这些位的8长度字节数组,我怎样才能将它们转换成一个字节。

public byte bitsToByte(byte[] bits) {
 //Something in here. Each byte inside bits is either a 1 or a 0.
}

有人可以帮忙吗?

由于

2 个答案:

答案 0 :(得分:3)

public static byte bitsToByte(byte[] bits){
    byte b = 0;
    for (int i = 0; i < 8; i++)
        b |= (bits[i]&1) << i;
    return b;
}

//as an added bonus, the reverse.
public static byte[] bitsToByte(byte bits){
    byte[] b = new byte[8];
    for (int i = 0; i < 8; i++)
        b[i] = (byte) ((bits&(1 << i)) >>> i);
    return b;
}

答案 1 :(得分:-1)

对于数组中的每个left shift,首先

bit为1,然后将该位添加到byte

该实现基于以下假设:阵列中的first位是符号位,后面的位是字节中较高位置到较低位置的大小。

public byte bitsToByte(byte[] bits) {
  byte value = 0;
  for (byte b : bits) {
    value <<=1;
    value += b;
  }
  return value;
}

测试方法:

public static void main(String[] args) {
  BitsToByte bitsToByte = new BitsToByte();
  byte bits[] = new byte[]{0,0,1,0,1,1,0,1};  // 1 + 0 + 4 + 8 + 0 + 32 + 0 + 0
  byte value = bitsToByte.bitsToByte(bits);
  System.out.println(value);
}

输出:

45

byte数组转换为byte值(按相同顺序):

public static byte bitsToByte1(byte[] bits){
  byte result = 0;
  for (byte i = 0; i < bits.length; i++) {
    byte tmp = bits[i];
    tmp <<= i;             // Perform the left shift by "i" times. "i" position of the bit
    result |= tmp;         // perform the bit-wise OR 
  }
  return result;
}

输入:(反向相同的数组)

  byte bits1[] = new byte[]{1,0,1,1,0,1,0,0};
  value = bitsToByte1(bits1);
  System.out.println(value);

输出:

45