0

What is use of << I understand in array it is used for push but here I am not clear what is purpose of this in following code. Where it is being used integer.

def array_pack(a)
    a.reverse.reduce(0) { |x, b| (x << 8) + b }
end

array_pack([24, 85, 0]) # will print 21784

like if I x is 8 and I write 8 << 8 it gives me response of 2048 so is it converting in bytes? or what exact is its purpose.

Kamal Panhwar
  • 2,345
  • 3
  • 21
  • 37

2 Answers2

2

It is a Bitwise LEFT shift operator.

Definition:

The LEFT SHIFT operator << shifts each bit of a number to the left by n positions.

Example:

If you do 7 << 2 = 28

7 in Base 2: 0000 0111

    128 64 32 16  8 4 2 1
    ---------------------- 
7:   0  0  0  0   0 1 1 1

Now shift each bit to the left by 2 positions

    128 64 32 16  8 4 2 1
    ---------------------- 
28:  0  0  0  1   1 1 0 0

Why?

Bitwise operators are widely used for low-level programming on embedded systems to apply a mask (in this case to integer)

Benefits

See this SO answer: link

View Source for more details: link

Sajjad Umar
  • 131
  • 8
1

As the documentation says, Integer:<< - Returns the integer shifted left "X" positions, or right if "X" is negative. In your scenario is shifts 8 positions to the left.

Here is how it works:

8.to(2) => "1000"

Now let's shift "1000" 8 positions to the left

(8 << 8).to_s(2) => "100000000000"

If you count the 0 above you will see it added 8 after "1000".

Now, let's see how it returns 2048

"100000000000".to_i(2) => 2048
razvans
  • 3,172
  • 7
  • 22
  • 30