How this bitshift to build the number works?

58 views Asked by At

I saw this method which is used for faster reading of positive value of Long.

public static long readLong(InputStream in) throws IOException {
    long n = 0;
    int c = in.read();
    while (c < 48 || c > 57) {
        c = in.read();
    }
    while (c >= 48 && c <= 57) {
        n = (n<<3) + (n<<1) + (c-'0');
        c = in.read();
    }

    return n;
}

While I understand all of the part, what I'm not able to get is this:
bit shifting by odd number to build the number n = (n<<3) + (n<<1) + (c-'0');

Why ignore the 3rd bit and how it's able to build it?

If anyone of you could explain me in simple way, it would be very much helpful.
Thanks!

3

There are 3 answers

1
dejvuth On

n << i is n * 2^i. So,

(n<<3) + (n<<1) = (n * 2^3) + (n * 2^1) = n * (2^3 + 2^1) = n * 10

Basically, it means to shift the value of n one digit to the left.

Adding it with c + '0' means adding the last digit with the integer value of c.

0
Uma Kanth On

Consider this code,

while (c >= 48 && c <= 57) {
             n = (n<<3) + (n<<1) + (c-'0');
             System.out.println(n);
             c = System.in.read();
         }

If I enter 123456, it prints

1
12 // 1 * 10 + 2
123 // 12 * 10 + 3
1234 // 123 * 10 + 4
12345 // 1234 * 10 + 5
123456 // 12345 * 10 + 6 

So what it basically does is making space at the units place for the next number by just multiplying it by 10 and adding the int value of the character.

0
dosw On

This is what happens:

  • (n<<3) means (n*8)
  • (n<<1) means (n*2)
  • (c-'0') gives you the character as int value

Together this means

n = n*10 + theNewDigit