Left shift operation in Crystal?

Hello,

I would like to do left shift operation on numbers, such as 1 << 32 which should give me 2^32.
Do you know how to do it in Crystal?

why not just 2**32

I’m pretty sure this is already a thing. https://crystal-lang.org/api/Int.html#<<(count%3AInt)-instance-method.

EDIT: https://play.crystal-lang.org/#/r/6xmn Note that im telling it the numbers are Int64, otherwise it would overflow and the output would be 0. Or, in future versions would raise an exception.

Thank you for you answer, indeed I was getting 0 because of the overflow.
Looking for ‘bit’ or ‘<<’ in the doc was not leading me toward the leftshift so i was thinking it was not the way to do it. Thank you for pointing me to the right documentation!

1 Like

Could you also explain me why
pp 56&-1
is giving 55? I mean -1 in the 2-complement representation is 0xFFFF… , but pp 56&0xFFFF is giving me the correct result (56).

You’re hitting the new “skip overflow check” operator &-, so your code is equivalent to pp 55.&-(1) not pp 55.&(-1).

2 Likes