Returns a byte array of at least length 1 : Binary Bit « Language Basics « Java






Returns a byte array of at least length 1

  


import java.util.BitSet;

public class Main {
  public static void main(String[] argv) throws Exception {
    BitSet bitset = new BitSet();
    bitset.set(1);
    System.out.println(toByteArray(bitset));
  }

  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 examples in the same category

1. Utility for byte swapping of all java data types
2.Bitwise DemoBitwise Demo
3.Binary Digits
4.Using the bitwise operatorsUsing the bitwise operators
5.Bitwise complement (~): inverts ones and zeroes in a number
6.Convert a number to negative and back
7.Bitwise AND (&)
8.Bitwise OR (|)
9.Bitwise XOR (^)
10.Left shift (<<)
11.Performing Bitwise Operations on a Bit Vector
12.Converting Between a BitSet and a Byte Array
13.Shift to the left
14.Signed shift to the right
15.Unsigned shift to the right
16.Bit-level unpacking of floating-point data
17.Gets the a single bit of the target.
18.Returns 16 bits from the long number.
19.Sets a specific bit of an int.
20.Fuses the lower 16 bits of two ints.
21.Class to represent unsigned 32-bit numbers.
22.A list of bits.
23.Gets the specified bit (0-31) from the integer argument.
24.Sets the specified bit (0-31) in the integer argument.
25.Clears a range of bits in the specified integer.