0

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?

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
Cork Kochi
  • 1,783
  • 6
  • 29
  • 45
  • Possible duplicate of [C - Using bit-shift operators for base conversion](https://stackoverflow.com/questions/20884181/c-using-bit-shift-operators-for-base-conversion) – NappingRabbit Jun 19 '18 at 13:49
  • your question is not really `Java` specific. The answer may be found here: https://stackoverflow.com/questions/20884181/c-using-bit-shift-operators-for-base-conversion – NappingRabbit Jun 19 '18 at 13:50
  • I don't see what this has to do with decimal to hex conversion. You're trying to convert **a** number (in any representation) to left-shifting a single bit and then subtracting one. This will only work for a limited set of numbers - and it's not decimal to hex conversion. – Erwin Bolwidt Jun 19 '18 at 13:53
  • 1
    If I understand correctly, you want to know a method to calculate the `x` in `(1 << x) - 1 = input`, where the `input` is `36028797018963967` or `127` in your examples? – Kevin Cruijssen Jun 19 '18 at 14:00

2 Answers2

2

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
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • Maybe I misunderstood OP's description, but isn't this doing the reversed of what is asked? How I understand the question is calculating `x` in `(1 << x) - 1 = input`, for any possible `input` (where the `127` and `36028797018963967` were examples given). But perhaps I just misunderstood. I'll ask OP to verify. – Kevin Cruijssen Jun 19 '18 at 14:02
  • Ah, smart. It's indeed just `.bitLength()`. Hadn't thought about that. +1 from me. :) – Kevin Cruijssen Jun 19 '18 at 14:10
2
System.out.println((1L << 55) - 1); //36028797018963967
xingbin
  • 27,410
  • 9
  • 53
  • 103