如何将字节转换为位?

Sup*_*eme 7 java

我有一个字节数组.我想访问每个字节并希望它的等效二进制值(8位),以便对其执行下一个操作.我听说过BitSet,但有没有其他方法可以解决这个问题?

谢谢.

MAK*_*MAK 9

如果你只需要二进制的String表示,你可以简单地使用Integer.toString()可选的第二个参数设置为2表示二进制.

要对任何整数类型执行通用位,必须使用逻辑和bitshift运算符.

// tests if bit is set in value
boolean isSet(byte value, int bit){
   return (value&(1<<bit))!=0;
} 

// returns a byte with the required bit set
byte set(byte value, int bit){
   return value|(1<<bit);
}
Run Code Online (Sandbox Code Playgroud)


Car*_*arl 5

您可能会在Guava Primitives包中找到与您正在查找的内容类似的内容。

或者,您可能想写一些类似的东西

public boolean[] convert(byte...bs) {
 boolean[] result = new boolean[Byte.SIZE*bs.length];
 int offset = 0;
 for (byte b : bs) {
  for (int i=0; i<Byte.SIZE; i++) result[i+offset] = (b >> i & 0x1) != 0x0;
  offset+=Byte.SIZE;
 }
 return result;
}
Run Code Online (Sandbox Code Playgroud)

这没有经过测试,但想法就在那里。还可以轻松修改循环/分配以返回其他内容的数组(例如,intlong)。

  • 会给这个+1,除非你使用了“否则”这个词。 (2认同)

Jig*_*shi 1

byte ar[] ;
byte b = ar[0];//you have 8 bits value here,if I understood your Question correctly :)
Run Code Online (Sandbox Code Playgroud)