14

I have picked up this example which converts BitSet to Byte array.

public static byte[] toByteArray(BitSet bits) {
    byte[] bytes = new byte[bits.length()/8+1];
    for (int i=0; i<bits.length(); i++) {
        if (bits.get(i)) {
            bytes[bytes.length-i/8-1] |= 1<<(i%8);
        }
    }
    return bytes;
}

But in the discussion forums I have seen that by this method we wont get all the bits as we will be loosing one bit per calculation. Is this true? Do we need to modify the above method?

kklw
  • 858
  • 3
  • 13
  • 28
JavaBits
  • 2,005
  • 11
  • 36
  • 40
  • the link http://www.exampledepot.com/egs/java.util/Bits2Array.html is expired, do you remember what was the example? – Vishrant Jul 18 '18 at 01:02

4 Answers4

15

No, that's fine. The comment on the post was relating to the other piece of code in the post, converting from a byte array to a BitSet. I'd use rather more whitespace, admittedly.

Also this can end up with an array which is longer than it needs to be. The array creation expression could be:

byte[] bytes = new byte[(bits.length() + 7) / 8];

This gives room for as many bits are required, but no more. Basically it's equivalent to "Divide by 8, but always round up."

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
10

If you need the BitSet in reverse order due to endian issues, change:

bytes[bytes.length-i/8-1] |= 1<<(i%8);

to:

bytes[i/8] |= 1<<(7-i%8);

Lars Lynch
  • 291
  • 3
  • 4
3

This works fine for me. if you are using Java 1.7 then it has the method toByteArray().

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Kamahire
  • 2,149
  • 3
  • 21
  • 50
  • 1
    By the way: the official name is "Java 7" (just as it was since Java 5, but Java 5 was still often called Java 1.5. Java 6 was *rarely* called Java 1.6). – Joachim Sauer Jun 01 '11 at 07:50
  • @Joachim Sauer, Yeah official name Java 7. I just mention the version. Any way thanks to correct me. – Kamahire Jun 01 '11 at 07:53
  • 3
    Be careful with BitSet.toByteArray() because it may not serialize the bytes in the order you expect. `BitSet notEqual = BitSet.valueOf(bitset.toByteArray()); // This doesn't work.` – Ryan Nov 06 '13 at 21:26
1

FYI, using

bits.length()

to fetch the size of the bitset may return incorrect results; I had to modify the original example to utilize the size() method to get the defined size of the bitset (whereas length() returns the number of bits set). See the thread below for more info.

java.util.BitSet -- set() doesn't work as expected

Community
  • 1
  • 1
ryanbwork
  • 2,123
  • 12
  • 12
  • `length` also does something else: `BitSet bits = new BitSet(16); System.out.println("BITSET LEN=" + bits.size());` gives: `BITSET LEN=64` (bit-size of memory used I guess). – alwi Sep 19 '16 at 08:56