[Tutor] testing the bits of a binary number

alan.gauld at yahoo.co.uk alan.gauld at yahoo.co.uk
Tue Apr 26 07:14:36 EDT 2022


   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. Personally I
   tend to omit the shifting and just create N masks and compare the original
   data to each mask, but that only makes sense for small bit sizes, say 16
   max. I name the masks after the purpose of the bit(s) tested so it looks
   like
   If data & motor_on:
       ...
   HTH
   Alan G 
   Ps posting from phone, apologies for the top post... 
   On 26 Apr 2022 11:37, Phil <phillor9 at gmail.com> wrote:

     I've been experimenting with a simpler way of testing the bits of a
     number without success.

     Say I have a number represented as 0b00001001 and I want to test which
     bits are set. I solved this originally as I would in assembly language
     by anding a bit mask and the number. The number and the bit mask are
     shifter left followed by another anding operation until the most
     significant bit is reached.

     This does work but it seems unnecessarily complex when using a high
     level language. An Internet search shows that similar questions have
     been asked and answerers given but I haven't been able to adapt those
     answerers to my problem. Can this problem be solved in a Pythonic way?

     --
     Regards,
     Phil

     _______________________________________________
     Tutor maillist  -  Tutor at python.org
     To unsubscribe or change subscription options:
     https://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list