开发者

Set a BitSet as a primitive type?

In Java, can you create a BitSet of size 8 and store it as a 开发者_如何学Pythonbyte in order to output it? The documentation on BitSets doesn't mention it. Does that mean no?


You can't cast BitSet to byte.

You can write code to do what you want though. Given a BitSet named bits, here you go:

byte output = 0;
for (int i = 0; i < 8; i++) {
    if (bits.get(i)) {
        output |= 1 << (7 - i);
    }
}

Update: The above code assumes that your bits are indexed 0 to 7 from left to right. E.g. assuming the bits 01101001 you consider bit 0 to be the leftmost 0. If however you're assigning the bits from right to left then bit 0 would be the rightmost 1. In which case you want output |= 1 << i instead.


There's nothing built in for that. You could implement that yourself obviously.


bit set is an array of bits

the JVM uses a 32-bit stack cell ie each register in the JVM stores one 32-bit address

we know that primitive boolean is set to be 1 bit but handled as 32 bit. array of boolean will be considered to be array of bytes

in BitSet each component of the bit set has a boolean value

Every bit set has a current size, which is the number of bits of space currently in use by the bit set. Note that the size is related to the implementation of a bit set, so it may change with implementation. The length of a bit set relates to logical length of a bit set and is defined independently of implementation.


The BitSet class is obviously not intended to export or import its bits to native datatypes and also quite heavy if you just want to deal with the fixed size of a single byte. It might thus not be what you need if you just want to manipulate the bits of a byte independently and then use the resulting byte. It seems you might just want to use a API like this:

SimpleBitSet bs = new SimpleBitSet( 'A' );
bs.setBit( 5 );
byte mybyte = bs.getByte();

So a implementation of such a simplified bit set could look like this:

public class SimpleBitSet
{
    private byte bits;

    public SimpleBitSet( int bits )
    {
        this.bits = (byte) bits;
    }

    public byte getByte()
    {
        return bits;
    }

    public boolean getBit( int idx )
    {
        checkIndex( idx );
        return ( bits & ( 1 << idx ) ) != 0;
    }

    public void setBit( int idx )
    {
        checkIndex( idx );
        bits |= 1 << idx;
    }

    public void clearBit( int idx )
    {
        checkIndex( idx );
        bits &= ~( 1 << idx );
    }

    protected void checkIndex( int idx )
    {
        if( idx < 0 || idx > 7 )
            throw new IllegalArgumentException( "index: " + idx );
    }    
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜