Home > Back-end >  How to create a 8bit array where the array can only store 0 and 1 in java
How to create a 8bit array where the array can only store 0 and 1 in java

Time:11-30

How to convert the number(random integer within 0 – 255) to binary and store the bit into an 8 bit array.(java)

CodePudding user response:

You may look at BitSet class, which implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined:

BitSet myByte = new BitSet(8);

To convert the byte value to the BitSet, there are methods BitSet.valueOf and BitSet::toByteArray:

byte b = 111;
BitSet bits = BitSet.valueOf(new byte[]{b});

byte fromBits = bits.toByteArray()[0];

CodePudding user response:

You can use Bit Masking to convert an int to binary.

public static int[] getBits(int number) {
    assert (0 <= number && number <= 255);
    int[] bits = new int[8];
    for (int i = 7; i >=0; i--) {
        int mask = 1 << i;
        bits[7-i] = (number & mask) != 0 ? 1 : 0;
    }
    return bits;
}
  • Related