Reputation:
I'm am using java longs to store bit sequences, and I want to edit them with a given position. Firstly, here is how I declare and initialize my bits.
long singleBit = 0b0000000000000000000000000000000000000000000000000000000000000000L;
First of all, is there any easier way to initialize a 64bit in java? Anyways, I then use the shift left operator to try and edit the bit sequence.
System.out.println(Long.toBinaryString( singleBit | 1 << 62));
Basically what I want is to insert a 1 on the 62nd index of this sequence, but when I print it out, it gives me this:
1000000000000000000000000000000
Clearly lacking a lot of trailing 0s. It also malfunctions for the 63rd index, and many others towards the end of the sequence. Is there any reason for this? I am fairly comfortable with bit operations but this has me puzzled. If, instead of using just "1" in the shift statement, I use something like this in its place :
long oneBit = 0b0000000000000000000000000000000000000000000000000000000000000001L;
then it works, but it throws off my OR statement. Is there a reason that this one is not behaving correctly? Thanks.
Upvotes: 0
Views: 171
Reputation: 40024
You should check out BitSet. It is used primarily for manipulating arbitrarily large bit strings but you can work with any size. It has many methods that are very useful. Here is how one might do what you were trying.
BitSet b = new BitSet();
b.set(62);
System.out.println(Long.toBinaryString(b.toLongArray()[0]));
// or
b.set(10,23);
System.out.println(b.toString()); // shows just the bits that are set
System.out.println(Long.toBinaryString(b.toLongArray()[0]));
Prints
100000000000000000000000000000000000000000000000000000000000000
{10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 62}
100000000000000000000000000000000000000011111111111110000000000
Upvotes: 0
Reputation: 83527
First of all, is there any easier way to initialize a 64bit in java?
Yes, use hex instead:
long singleBit = 0x00000000;
If you want to explicitly set the first bit without any bit operations, you can do
long singleBit = 0x80000000;
Basically what I want is to insert a 1 on the 62nd index of this sequence, but when I print it out, it gives me this:
This is because 1
is an int
. Use 1L
for a long
literal.
Upvotes: 1
Reputation: 59144
The problem is 1 << 62
1
is an int
(32 bits), not a long
. Surprisingly, on many architectures, when you shift an int
, only the lower 5 bits of the shift are used.
The shift you specified as 62 ends up being (62%32) = 30.
Upvotes: 1