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.
1is anint, not along.<<has a higher operator precedence than the bitwise OR|, so1 << 62runs first. There's a problem here though:1and62are both 32-bit integers, so when you shift left 62 bits, it has to roll over when it runs out of bits. So it does shift over 62 bits, it just went over all 32 bits, wrapped around, and went another 30 bits, so when you print it, you get the appropriate 30 trailing zeroes.0b0000000000000000000000000000000000000000000000000000000000000000Lis equivalent to0Lin Java. There's no reason to type out all those zeroes, both ways will compile to the exact same byte code.