Java Java7

BitSet.valueOf() and toByteArray()

BitSet.valueOf() and toByteArray()

BitSet.valueOf() and toByteArray()

The BitSet class in Java 7 was enhanced with methods to easily convert between BitSets and byte/long arrays, useful for serialization and bitmasking.

How it Works

BitSet.valueOf(byte[]) creates a BitSet from a byte array. toByteArray() does the opposite. This allows for easy storage or network transmission of bit-level data structures.

Java Example

import java.util.BitSet;

public class BitSetExample {
    public static void main(String[] args) {
        BitSet bits = BitSet.valueOf(new byte[]{0b0101});
        System.out.println("Bit 0: " + bits.get(0));
        System.out.println("Bytes: " + bits.toByteArray().length);
    }
}

Output

Bit 0: true
Bytes: 1

Key Points

  • Convert BitSet to/from arrays
  • Simplifies bit data persistence
  • Useful for network protocols
  • Supports both byte and long arrays
Topics: Java Java7
← Newer Post Older Post →