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..
bytearr = bits.toBytes();
Also, I need to be able to convert from a byte array into a BitSet..
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(bitS et.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(byteA rr);
try {
ObjectInputStream ois = new ObjectInputStream(bais);
bitSet2 = (BitSet)ois.readObject();
}
catch (Exception ex) {
ex.printStackTrace();
}
// check :
System.out.println(bitSet. equals(bit Set2));
...
this code is good for all objects that implements java.io.Serializable - not only for BitSet.
-gkern
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(bitS
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(byteA
try {
ObjectInputStream ois = new ObjectInputStream(bais);
bitSet2 = (BitSet)ois.readObject();
}
catch (Exception ex) {
ex.printStackTrace();
}
// check :
System.out.println(bitSet.
...
this code is good for all objects that implements java.io.Serializable - not only for BitSet.
-gkern
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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
ASKER
bytearr = bits.toByteArray();
bytearr = toByteArray(bits);