[Tutor] I don't quite understand bitwise

Steve Willoughby steve at alchemy.com
Tue Dec 15 16:39:28 EST 2020


On Tue, 2020-12-15 at 19:11 +0000, nathan tech wrote:
> So I started to research how the x|y format works and came across 
> bitwise operators which is apparrently what is meant when x|y|z is
> used.
> 
> But to me they look like ints/

Yes, they are, in fact, ints. The bitwise-OR (|) is a math operator
that acts on two integer values.

Say x = 0b1010 and y = 0b1100.
If you go bit-by-bit and apply the OR operation on the corresponding
bits of x and y, you get:

x   1010
y   1100
x|y 1110

so in python the result of x|y is 0b1110, or 14 in decimal.

This kind of thing has a long history in C and other languages for
specifying a set of options as a single integer parameter to a
function.

So if, say, you could have any combination of OPTA, OPTB, and OPTC as
"flags" to pass to a function, you could assign

OPTA = 0b001
OPTB = 0b010
OPTC = 0b100

and you could pass the parameter as 0, OPTA, OPTB|OPTC, OPTA|OPTC, etc.
Respectively that would be the values 0, 0b001, 0b011, 0b101, etc. as
the called function would see them.


More information about the Tutor mailing list