[Tutor] testing the bits of a binary number

Cameron Simpson cs at cskk.id.au
Tue Apr 26 21:00:01 EDT 2022


On 26Apr2022 21:20, Phil <phillor9 at gmail.com> wrote:
>
>On 26/4/22 21:14, alan.gauld at yahoo.co.uk wrote:
>>Bit operations will be fastest but you could convert to a binary 
>>string and do a character search if you think that is more elegant.
>
>Thank you Alan for your reply and it looks like bit shifting is the 
>only real way to solve the problem.

To an extent it depends on what question you are really trying to 
answer.

My own experience is that I'm usually concerned only with the 
combination of bits involved. Made up example:

    if flags & F_MODE1:
        # mode 1, we expect no other bits
        flags &= ~F_MODE1
        if flags:
            raise ValueError("MODE1 set, unexpected other bits: %s" % bin(flags))
        ... do the mode 1 stuff ...
    elif flags & F_MODE2:
        flags &= ~F_MODE1
        submode = False
        if flags & F_MODE2_SUBMODE:
            flags &= ~F_MODE1
            submode = True
        if flags:
            raise ValueError("MODE2 set, submode=%s, unexpected other bits: s" (submode, bin(flags)))
        ... do the mode 2 stuff ...
    else:
        ... whatever ...

So in the above example I'm interested in specific bits, and want to 
know if any bits are unparsed.

What's your use case? Or is this a learning exercise around bit 
manipulation, which is also just fine?

Also, you can at least print the binary form with the bin() function.

Finally, enums provide a nice Pythonic way of representing bitmaps:
https://docs.python.org/3/library/enum.html#module-enum

That might help you with testing and representation.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list