1

Possible Duplicate:
Converting decimal to binary in Java

I have found this code that takes as an input a number x, an array p and another number pmax which indicates the size of the array p

public static int permute(int x, int p[], int pmax) {
    int y = 0;

    for (int i = 0; i < p.length; ++i) {
        y <<= 1;
        y |= (x >> (pmax - p[i])) & 1;
    }

    return y;
}

this code should be permutating the bits of the first byte that is stored in the number x according to the rules defined in the array p

so for example if the first pmax bits of x are 101 and the array p is the following: p={2 1 3} then the result of this function(y) will be equal to 011

Question

I have never worked with bitwise operators and I would like to see all the intermediate results of the above code. For example what does y<<=1 do and why it is used. To do this I need to somewhat display the y variable in the binary form, otherwise I just get some random decimals which doesn't help me understand anything.

So how can I display after each bitwise operation the result in binary format?

If this is not a good method to learn exactly what this code does, what method would you suggest?

Community
  • 1
  • 1
ksm001
  • 3,772
  • 10
  • 36
  • 57

2 Answers2

5

Integer.toBinaryString(int x) will do this for you.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • I'd rather close this question as an easy duplicate than award the fastest gun in the west and his deputies 10 XP each. – John Dvorak Jan 04 '13 at 16:54
  • 1
    @JanDvorak The linked duplicate is related to writing a handmade method that converts the number to generate the binary string. I even voted this question to be closed but this doesn't imply I can't spend 10 seconds of my time answering in the meanwhile. If it's going to be closed then it will happen anyway. – Jack Jan 04 '13 at 16:57
3

are you looking for Integer.toBinaryString(int i) ?

PermGenError
  • 45,977
  • 8
  • 87
  • 106
Kent
  • 189,393
  • 32
  • 233
  • 301