Doubt on how to use Shift in Java

Asked

Viewed 315 times

1

Well, I have a question about how to use Shift Left in java. I have a String representing a hexadecimal value. Only I need to pass this value to binary. For this I use an integer variable to turn this string into a decimal number:

int primeiroOperando = Integer.parseInt(addR2, 16);

And to turn it into binary, I use toBinaryString:

String addR1 = Integer.toBinaryString(primeiroOperando);

But, since I need to do Shift, because I have to take the least significant bits, I can’t use this String because I have to use an integer for this. How can I do this binary conversion to save to an entire variable and so be able to do Shift?

1 answer

1


Binary is just a representation. You can use shift with decimal, hexadecimal, etc, as shown in the example below:

    int i = 7;
    int x = i >> 1;
    int y = i << 2;
    System.out.println(String.format("i=%d, x=%d, y=%d", i, x, y)); // i=7, x=3, y=28
  • 2

    Igor, the shift is a bit-level operation, so it is totally independent of the number display scheme. Try to transform the example of Murillo here in binary, can facilitate the understanding of the operation.

  • Now I understand, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.