I
I
indeterminate2019-04-12 12:38:10
Java
indeterminate, 2019-04-12 12:38:10

How to understand how this method works in ShowBits?

I'm reading "Java 8 Beginner's Guide" by Schildt, read up to page 199 and then there was a gag. The author describes the ShowBits class, which should show the binary representation of any number. Inside this class there is a show method, but I did not understand how it works at all. The author himself also does not explain anything, after the program code comes the next section of the chapter.
Here is the class code

class ShowBits {
    int numbits;
    
    ShowBits(int n) {
        numbits = n;
    }
    
    void show(long val) {
        long mask = 1;
        
        // Сдвинуть значения 1 влево на нужную позицию
        mask <<= numbits-1;
        
        int spacer = 0;
        for(; mask != 0; mask >>>= 1) {
            if((val & mask) != 0) System.out.print("1");
            else System.out.print("0");
            spacer++;
            if((spacer % 8) == 0) {
                System.out.print(" ");
                spacer = 0;
            }
        }
        System.out.println();
    }
}

With the preservation of the author's comments.
Help me understand this please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
crazywu, 2019-04-12
@indeterminate

Everything is quite simple.
First, a mask is created from zeros and a leading one mask.
Further, the unit is shifted in a cycle along this mask and the logical operation and is performed with the function argument.
if the result of the logical operation is 0, then for the current position of the unit in the mask, the argument at the same position has 0, if the value is different from zero, it is one. Accordingly, they are displayed on the screen.
spacer is just a way to separate the output bits into groups of 8 with a space.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question