Reputation: 377
if I set two different bits in a Bitset
BitSet x= new BitSet(8);
x.set(0);//.........Case1
x.set(7);//.........Case2
In which case I m setting the most significant bit?
Upvotes: 2
Views: 1842
Reputation: 24740
The LSB is index 0.
Example:
Let's create the character 'a'
(binary 0110 0001
).
Please note: Adding the bits left-to-right, translates in running down from index 7 to 0.
BitSet bitSet = new BitSet(8);
bitSet.set(7, false);
bitSet.set(6, true);
bitSet.set(5, true);
bitSet.set(4, false);
bitSet.set(3, false);
bitSet.set(2, false);
bitSet.set(1, false);
bitSet.set(0, true);
// let's convert it to a byte[]
byte[] array = bitSet.toByteArray();
// and let's convert that byte[] to text now.
String someText = new String(array, Charsets.US_ASCII);
// this will print an 'a'
System.out.println(someText);
Which is the same as (JDK7+):
System.out.println((char)0b01100001);
Upvotes: 1
Reputation: 27287
A bit set is not a huge number. It's a set (technically, a vector/list/infinite array) of bits. There is not even a method of BitSet
converting it to a number.
Concerning the internal representation - that is implementation dependent. While an implementation could choose to store bit 0 as the least significant bit of the first integer in its internal array, that is not set in stone. I think the Sun implementation does this (except it uses an array of longs, not ints).
There is, however, a natural bijection between bitSets and integers. A bit set is intexed from 0 upwards, and any non-negative integer can be represented as a bitSet uniquely in a natural way as a binary number with the least significant bit stored as a bit 0. Under this bijection, bit 7 is more significant than bit 0, but for every bit in the bit set, each next bit is even more significant.
Upvotes: 2
Reputation: 533520
While the most significant bit is purely subjective for a BitSet, but setting both ends you could say one of them is likely to be the most significant, but you could say which one it was. ;)
If you want to set the most (and least) significant bit of a byte you can do
byte b = (byte) ((1 << 7) | (1 << 0));
or
byte b = 0;
b |= 1 << 0;
b |= 1 << 7;
Upvotes: 0