9.5 Bitwise operators

Hollywood supports the following bitwise operators:

The bitwise operators allow you to work with expressions on bit level. Those operations are all limited to 32-bit values. Here is a description of the bitwise operators:

The left shift operator (<<) shifts all bits of the operand a left b times. The bit holes on the right side of the number created by this operation will be padded with zeros (logical shift). b must not be negative. Shifting a x times left is equal to multiplying this number by 2^x. But of course, shifting is much faster than multiplying. Examples:

 
7 << 1 = %111 << 1 = %1110 = 14 (7 * 2^1 = 14)
256 << 4 = %100000000 << 4 = %1000000000000 = 4096 (256*2^4=4096)

The right shift operator (>>) shifts all bits of the operand a right b times. The bit holes on the left side of the number will be padded with zeros (logical shift). If you need an arithmetic shift (bit holes will be padded with the most significant bit), please use the Sar() function instead. b must not be negative. Shifting a right x times is equal to dividing this number by 2^x. But of course shifting is much faster than dividing if an integer result is precise enough for your purpose. Here are some examples:

 
65 >> 1 = %1000001 >> 1 = %100000 = 32 (65\2^1=32)
256 >> 4 = %100000000 >> 4 = %10000 = 16 (256\2^4=16)

The bitwise And, Xor and Or operators are basically the same as the logical And / Xor / Or operator with the difference that &, ~ and | work on bit level, i.e. they compare all 32 bits of operands a and b and set the bits in the result according to this comparison. The And operator will set the bit in the return value if both bits in operands a and b are set on this position. The Xor operator will set the bit in the return value if one of the two bits are 1 but not if both are 1. The Or operator will set the bit in the return value if one or both of the operands have the bit set on that position. A table:

Examples:

 
%10011001 & %11101000 = %10001000   ; Bitwise And
%10011001 ~ %11101000 = %01110001   ; Bitwise Xor
%10011001 | %11101000 = %11111001   ; Bitwise Or

The unary negation operator (~) will do a bitwise inversion of the number it is used on. All bits will be inverted. Please note that the value will always be converted to a 32-bit integer before the inversion. Thus, you might get a lot of leading ones. For example:

 
~%00000000 = %11111111111111111111111111111111
~%10111001 = %11111111111111111111111101000110

To get rid of these 1s, simply use the bitwise And operator (&) on the resulting value. For instance, if you only want to have 8 bits inverted like in the example above, use the bitwise And with 255:

 
~%00000000 & %11111111 = %11111111
~%10111001 & %11111111 = %01000110


Show TOC