Java BitSet to bitSet2byte(BitSet b, int bytes)

Here you can find the source of bitSet2byte(BitSet b, int bytes)

Description

converts a BitSet into a binary field used in pack routines

License

Open Source License

Parameter

Parameter Description
b - the BitSet
bytes - number of bytes to return

Return

binary representation

Declaration

public static byte[] bitSet2byte(BitSet b, int bytes) 

Method Source Code


//package com.java2s;

import java.util.BitSet;

public class Main {
    /**//from   w  w  w .j a va  2  s  .com
     * converts a BitSet into a binary field used in pack routines
     * 
     * @param b - the BitSet
     * @param bytes - number of bytes to return
     * @return binary representation
     */
    public static byte[] bitSet2byte(BitSet b, int bytes) {
        int len = bytes * 8;

        byte[] d = new byte[bytes];
        for (int i = 0; i < len; i++) {
            if (b.get(i + 1)) {
                d[i >> 3] |= (0x80 >> (i % 8));
            }
        }

        if (len > 64) {
            d[0] |= 0x80;
        }
        if (len > 128) {
            d[8] |= 0x80;
        }

        return d;
    }

    /**
     * converts a BitSet into a binary field
     * used in pack routines
     * @param b - the BitSet
     * @return binary representation
     */
    public static byte[] bitSet2byte(BitSet b) {
        int len = (((b.length() + 62) >> 6) << 6);
        byte[] d = new byte[len >> 3];
        for (int i = 0; i < len; i++) {
            if (b.get(i + 1)) {
                d[i >> 3] |= (0x80 >> (i % 8));
            }
        }

        if (len > 64) {
            d[0] |= 0x80;
        }
        if (len > 128) {
            d[8] |= 0x80;
        }

        return d;
    }
}

Related

  1. Bitset2BitString(BitSet bitset, int length)
  2. bitset2bytes(BitSet bits, byte[] bytes)
  3. bitSet2extendedByte(BitSet b)
  4. bitSet2Int(BitSet bs)
  5. bitsetToDoubleArray(BitSet bs, int n)