페이지

2015년 11월 4일 수요일

Scala2e Chapter5 Basic Types and Operations 5.6 Bitwise operations

Scala enables you to perform operations on individual bits of integer types with several bitwise methods.

bitwise-and(&), bitwise-or(|), bitwise-xor(^), unary_~

scala> 1 & 2
res24: Int = 0
scala> 1 | 2
res25: Int = 3
scala> 1 ˆ 3
res26: Int = 2
scala> ~1
res27: Int = 2

The first expression, 1 & 2, bitwise-ands each bit in 1 (0001) and 2 (0010), which yiedls 0(0000).
The second expression, 1 | 2, bitwise-ors each ibt in the same operands, yielding 3(0011).
The third expression, 1 ^ 3, bitwise-xors each bit in 1(0001) and 3(0011), yielding 2(0010).
The final expressiion, ~1, inverts each bit in 1 (0001), yielding -2, which in binary looks like 11111111111111111111111111111110.

Scala integer type also offer three shift methods: shift left(<<), shift right(>>), and unsigned shift right(>>>).

scala> 1
>> 31
res28: Int = 1
scala> 1
>>> 31
res29: Int = 1
scala> 1 << 2
res30: Int = 4

-1 in binary is 11111111111111111111111111111111. In the first example,-1 >> 31, -1 is shifted to the right 31 bit positions.
Since an Int consisits of 32 bits, this operation effectively moves the leftmost bit over until it becomes the rightmost bit.
Since the >> method fills with ones as it shifts right, because the leftmost bit of -1 is 1, the result is identical to the original left operand, 32 one its, or -1.

In the second example, -1>>> 31, the leftmost bit is again shifted right until it is in the rightmost position, but this time filling with zeroes along the way. Thus the result this time is binary 00000000000000000000000000000001, or 1. In the final example, 1 << 2,
the left operand, 1, is shifted left two positions (filling in with zeroes), resulting in binary 00000000000000000000000000000100, or 4.




댓글 없음: