360 Β° rotation "function" in bit shift operators F #

Bit shift operators in F # are documented as not performing rotation when shifting bits beyond the end of a value. You can see this in F # Interactive:

  > let a = 128uy
 - a << & lt 1 ;;

 val a: byte = 128uy
 val it: byte = 0uy

That is, we have shifted the top bit from the top of 128, indicating 0.

If F # turned the bits instead of moving them from the end, we would get 1 instead, since 1 bit in the MSB is turned to LSB .

However, if you make a small change in the second expression, you will get an amazing result:

  > let a = 128uy
 - a << & lt 8 ;;

 val a: byte = 128uy
 val it: byte = 128uy

Now, it looks like he made a complete bit-by-turn!

Why is this?

+4
source share
1 answer

What happens is that F # does modular arithmetic by value on the right side of the bit shift operator before doing the shift. It uses mod 8 for an unsigned byte, since the F # byte has 8 bits. Since 8 mod 8 is 0, it does not shift bits in a byte at all.

You can see this more clearly if you play a little with the values:

  > let a = 4uy
 - a << & lt 1 ;;

 val a: byte = 4uy
 val it: byte = 8uy

 > a <<< 9 ;;
 val it: byte = 8uy
 > a <<< 17 ;;
 val it: byte = 8uy

We get the same result in all three cases, because they are equivalent to expressions in mod 8.

The same thing happens with right shift ( >>> ), and the behavior is not limited to bytes.

+3
source

Source: https://habr.com/ru/post/1489374/


All Articles