[Tutor] Preference to Bitwise operators in comparison to Logical operators

Alan Gauld alan.gauld at yahoo.co.uk
Thu Sep 10 18:14:22 EDT 2020


On 10/09/2020 18:51, Manprit Singh wrote:

> As we all know True is 1 and False is 0 .
> Now
> (1)  if the operands are True or  False  to logical operators and , or, not
>  (2) and if operands are 1 or 0 to bitwise operators  x & y, x | y  and x ^
> 1
> serves the same purpose , only difference is Logical operators will return
> either True or False in this particular case .

Correct if and only if we restrict values to 1 and 0.

> Secondarily Bitwise operator gives extra operators  - XOR & Shifts

Shifts make no sense for logical booleans. They only work
with bit patterns.

XOR could be implemented for logic and there are occasional
uses for that. But its not hard to write a function if needed.

> Secondarily bitwise operators are faster too.

Usually, but that's an implementation issue.
Against that logical operators are much more adaptable across
data types. Bitwise operators can only meaningfully work on
integers.

But speed should hardly ever be a major influence on choosing a
programming structure  (despite what some C programmers seem
to think). The primary criteria should always be expression of
intent and reliability/maintainability. Only worry about speed
when you know you have a speed problem, and even then only
after you have optimised the algorithms. In fact in Python I'd
go as far as to say optimising speed by adopting bitwise
operations should never be needed because there will be
better ways of doing it. (eg. Writing C wrappers or using
Cython, Boost etc.) If you are choosing Python bitwise operators
for speed reasons you probably have chosen the wrong language
for your project.

Bitwise operations are for twiddling bits. They work great with
the bitmasks returned by some hardware and OS interfaces. Or
in dealing with data read from files or networks originating
on different hardware (eg. uncommon encodings etc)

Logical operations are for expressing logical choices and decisions
in code. Controlling loops, switches, branches etc. If you are
working with boolean values use logical operators not
bitwise ones. If you are working with hardware (eg Raspberry Pi,
USB, OS system level calls) you may need to go bitwise.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list