Cork Kochi
Cork Kochi

Reputation: 1891

using Bit Shift operations to convert from decimal to hex in Java

If I convert decimal 127 to hexadecimal in Java it will be 7f.
I can get the same output using:

(1 << 7) - 1 = 127
 0x7F = 127

I am trying to convert a decimal value 36028797018963967.
In hex it will be:

0x7fffffffffffff

How can I represent this in bit-shift? For example, the output should be (with the ? filled in):

(1 << ?) - 1 = 36028797018963967

Any (Java) code to get the output in this format?

Upvotes: 0

Views: 2100

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

You can use long or BigInteger.

public void test() {
    // Shifting to get the number.
    long l = (1L << 63) - 1L;
    System.out.println("" + l + " -> " + Long.toHexString(l));
    BigInteger bi = BigInteger.ONE.shiftLeft(63).subtract(BigInteger.ONE);
    System.out.println("" + bi + " -> " + bi.toString(16));
    bi = BigInteger.ONE.shiftLeft(55).subtract(BigInteger.ONE);
    System.out.println("" + bi + " -> " + bi.toString(16));
    // Finding the amount to shift - it's easiest using BigInteger
    System.out.println(bi.bitLength());
}

Prints

9223372036854775807 -> 7fffffffffffffff

9223372036854775807 -> 7fffffffffffffff

36028797018963967 -> 7fffffffffffff

55

Upvotes: 2

xingbin
xingbin

Reputation: 28279

System.out.println((1L << 55) - 1); //36028797018963967

Upvotes: 2

Related Questions