Search code examples
javabytejava-6bitset

How can I write bits to a byte?


I currently have 16 bits I want to set to variables (2 separate bytes). I've used the BitSet object to hold my bits and while in Java 1.7 there is a toByteArray() method, I need something that works on earlier versions of Java. It doesn't need to use BitSet, but I would prefer that it does (if possible).

If someone could tell me how to write something like 01101011 to a byte, I think that would help me enough. Thanks!


Solution

  • You can use this piece of code to do that:

    public static byte convert(BitSet bits, int offset) {
      byte value = 0;
      for (int i = offset; (i < bits.length() && ((i + offset) < 8)) ; ++i) {
        value += bits.get(i) ? (1 << i) : 0;
      }
      return value;
    }
    

    So to convert two bytes you will do:

    BitSet b = ....;
    byte b1 = Helper.convert(b, 0);
    byte b2 = Helper.convert(b, 8);