开发者

How to convert a byte into bits?

I have one array of byte开发者_如何转开发s. I want to access each of the bytes and want its equivalent binary value(of 8 bits) so as to carry out next operations on it. I've heard of BitSet but is there any other way of dealing with this?

Thank you.


If you just need the String representation of it in binary you can simply use Integer.toString() with the optional second parameter set to 2 for binary.

To perform general bit twiddling on any integral type, you have to use logical and bitshift operators.

// 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);
}


You might find something along the lines of what you're looking in the Guava Primitives package.

Alternatively, you might want to write something like

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;
}

That's not tested, but the idea is there. There are also easy modifications to the loops/assignment to return an array of something else (say, int or long).


BitSet.valueOf(byte[] bytes)

You may have to take a look at the source code how it's implemented if you are not using java 7


Java has bitwise operators. See a tutorial example.

The Java programming language also provides operators that perform bitwise and bit shift operations on integral types. The operators discussed in this section are less commonly used. Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist.

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

A byte value IS integral, you can check bit state using masking operations. The least significant bit corresponds to the mask 1 or 0x1, the next bit correspond to 0x2, etc.

byte b = 3;
if((b & 0x1) == 0x1) {
    // LSB is on
} else {
    // LSB is off
}


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


Well I think I get what you mean. Now a rather substantial error with this is that it doesn't work on negative numbers. However assuming you're not using it to read file inputs, you might still be able to use it.

public static ArrayList<Boolean> toBitArr(byte[] bytearr){
    ArrayList<Boolean> bitarr = new ArrayList<Boolean>();
    ArrayList<Boolean> temp = new ArrayList<Boolean>();
    int i = 0;
    for(byte b: bytearr){
        while(Math.abs(b) > 0){
            temp.add((b % 2) == 1);
            b = (byte) (b >> 1);
        }
        Collections.reverse(temp);
        bitarr.addAll(temp);
        temp.clear();
    }
    return bitarr;
}


Here is a sample, I hope it is useful for you!

DatagramSocket socket = new DatagramSocket(6160, InetAddress.getByName("0.0.0.0"));
socket.setBroadcast(true);
while (true) {
    byte[] recvBuf = new byte[26];
    DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
    socket.receive(packet);
    String bitArray = toBitArray(recvBuf);
    System.out.println(Integer.parseInt(bitArray.substring(0, 8), 2)); // convert first byte binary to decimal
    System.out.println(Integer.parseInt(bitArray.substring(8, 16), 2)); // convert second byte binary to decimal
}
public static String toBitArray(byte[] byteArray) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            sb.append(String.format("%8s", Integer.toBinaryString(byteArray[i] & 0xFF)).replace(' ', '0'));
        }
        return sb.toString();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜