Previous Up Next

6.2.1  Basic operators: bitor bitxor bitand

Bitwise operators operate on the base 2 representations of integers, even if they are not presented in base 2. For example, the bitwise or (see Section 6.1.4) operator will take two integers and and return an integer whose base 2 digits are the logical ors of the corresponding base two digits of the inputs (see Section 6.1.4). Thus, to find the bitwise or of 6 and 4, look at their base 2 representations, which are 0b110 (the 0b prefix indicates that it’s in base 2, see Section 5.1) and 0b100, respectively. The logical or or their rightmost digits is 0 or 0=0. The logical or of their next digits is 1 or 0=1, and the logical or of their remaining digits is 1 or 1=1. So the bitwise or of 6 and 4 is 0b110, which is 6.

To work with bitwise operators, it isn’t necessary but it may be useful to work with integers in a base which is a power of 2. The integers can be entered in binary (base 2), octal (base 8) or hexadecimal (base 16) (see Section 6.4.1). To write an integer in binary, prefix it with 0b; to write an integer in octal, prefix it with 0 or 0o; and to write a integer in hexadecimal (base 16), prefix it with 0x. Integers may also be output in octal or hexadecimal notation (see Section 3.5.7, item 14).

There are bitwise versions of the logical operators or, xor and and; they are all prefixed operators which take two arguments, which are both integers.


Previous Up Next