Link to home
Start Free TrialLog in
Avatar of kmerkison
kmerkison

asked on

Convert BitSet to Byte Array

I'm doing a file compression program and I need to know how to convert a BitSet to a byte array.. I've tried using the following code, where bits is my BitSet and bytearr is defined as the byte array..

      bytearr = bits.toBytes();


Also, I need to be able to convert from a byte array into a BitSet..
Avatar of kmerkison
kmerkison

ASKER

I've also tried the toByteArray() function.. i may not be using the function properly.. not sure.. i've tried..

bytearr = bits.toByteArray();
bytearr = toByteArray(bits);
Hi,
try this code:
...
// init new bit set
  BitSet bitSet = new BitSet(10);
  bitSet.set(4);
  bitSet.set(8);
  bitSet.set(9);

  // convert from BitSet to byte array
  ByteArrayOutputStream baos = new ByteArrayOutputStream(bitSet.size());
  try {
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(bitSet);
  }
  catch (Exception ex) {
    ex.printStackTrace();
  }
  byte[] byteArr = baos.toByteArray(); // the byte array

  // convert back to BitSet
  BitSet bitSet2 = null; // the new BitSet
  ByteArrayInputStream bais = new ByteArrayInputStream(byteArr);
  try {
    ObjectInputStream ois = new ObjectInputStream(bais);
    bitSet2 = (BitSet)ois.readObject();
  }
  catch (Exception ex) {
    ex.printStackTrace();
  }

  // check :
  System.out.println(bitSet.equals(bitSet2));
...


this code is good for all objects that implements java.io.Serializable - not only for BitSet.
-gkern
ASKER CERTIFIED SOLUTION
Avatar of Gidi Kern
Gidi Kern
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

-  Points for gkern

Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
Venabili
EE Cleanup Volunteer