Converting Between a BitSet and a Byte Array - Java Collection Framework

Java examples for Collection Framework:BitSet

Description

Converting Between a BitSet and a Byte Array

Demo Code

import java.util.BitSet;

public class Main {
  public static BitSet fromByteArray(byte[] bytes) {
    BitSet bits = new BitSet();
    for (int i = 0; i < bytes.length * 8; i++) {
      if ((bytes[bytes.length - i / 8 - 1] & (1 << (i % 8))) > 0) {
        bits.set(i);//from w  w  w  . ja  va2  s.co m
      }
    }
    return bits;
  }

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

Related Tutorials