cortesis
cortesis

Reputation: 1

Bitshift to 64'th Bit in Java

For a programm, i need to shift the bits from the first to the last bit. So i would need to:

long a = 0;
a |= 1L<<64;

Since the long isn't unsigned, it doesn't work. Is there a possibility to shift a 1 to this last Bit? I'm taking a long and not a BigInt, because i'm tried to use as few memory than possible.

Upvotes: 0

Views: 1742

Answers (3)

Thomas
Thomas

Reputation: 88707

Java will shift by num % sizeof(datatype) only, i.e. if you shift an int by 32 it will effectively be no shift at all. If you shift by 33 the effective shift will be 33 % 32 = 1.

The same is true for long just that the size of long is 64 and thus shifting by 64 is effectively no shift. The highest shift possible with long thus is 63 and that's what you need to get the last bit to position 64 (it already is at position 1 so you just need to shift by 63 places).

Upvotes: 4

Malt
Malt

Reputation: 30285

First of all, your code doesn't make a lot of sense. If you shift a long variable 64 places to the left, you should end up with zero, since you've shifted away all of the long's original bits.

Second, as you've correctly mentioned, Java treats all ints and longs as singed (as stated here). So it considers a 64 bit shift on a long to be equal to a 0 shift. That's why instead of getting zero, you're left with the original value, which is 1. If you want to initialize a to 1 followed by 63 zeroes I suggest avoiding shifts, and just using something like this:

long a = 0x8000_0000_0000_0000L;

It's readable by anyone who understands binary, and there's not Java bit shift magic involved.

If you want to keep using shift, just use a 63 shift instead:

long a|=1L<<63;

Upvotes: 0

Persixty
Persixty

Reputation: 8589

Shifting by 64 bits will have the effect of not shifting. Shifting by 63 bits will have desired output. Shift on long v << b shifts by b%64 bits. so 1L<<64 shifts by nothing.

public static void main (String[] args) throws java.lang.Exception
{
    long a=1L<<63;
    long b=1L<<64;
    System.out.println(Long.toBinaryString(a));
    System.out.println(Long.toBinaryString(b));
}

Expected output:

1000000000000000000000000000000000000000000000000000000000000000
1

Upvotes: 1

Related Questions