Python Forum
& vs % - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: & vs % (/thread-6572.html)



& vs % - Skaperen - Nov-29-2017

which is better:
    foo = bar % 256
or:
    foo = bar & 255
???

i just benchmarked them for speed.  the 2nd is slightly faster in python3.5.2.  in a loop of 1000000000 times, it was about 89.36 seconds for the 1st one to 81.53 seconds for the 2nd one, on my laptop.  is that enough reason to use the latter?  the code i will putting this in will probably run at most no more than 20 times a day.

i just tried them in python2.7.12 ... 60.12 seconds for the 1st vs. 49.55 seconds for the 2nd.


RE: & vs % - buran - Nov-29-2017

my error, sorry


RE: & vs % - DeaD_EyE - Nov-29-2017

The & is a logical bitwise and operation:

111111112 & 1000000002 == 0
8bit               9 bit

The modulus operator % returns the rest of an division. It's a different behavior as the bitwise and operation.
111111112 % 1000000002 == 111111112 == 25510
8 bit               9 bit                 8 bit

The question which is faster, does not help to gain performance win, because are giving different results.


RE: & vs % - Skaperen - Nov-29-2017

for this case, both do give the same result ... the low order 8 bits.  sure what is going on is different.  i was just wondering how much this might influence people's thought of "better".


RE: & vs % - wavic - Nov-29-2017

If you want to get the lower 8 bits use the & operator. It's more clear what is happening in the code. I haven't seen getting the bits that way ( using modulo ). Also, changing the value of the bar above 255 and it will not be the same anymore.


RE: & vs % - Skaperen - Nov-30-2017

turns out, at least one architecture (IBM 370) is faster when using % than when using &.  i believe the CDC 7600 is the same way.  so, at least, when coding in C, it is probably better to use %.  in the case of Python, the interpreter could, in theory, understand what are doing, and do it the best way.  but that didn't seem to happen.


RE: & vs % - wavic - Nov-30-2017

You guys have an experience. I am using Python for my own needs for now. Programming is not my job. Python is almost the only language I can actually do something. My C knowledge is too insignificant. A little HTML and JS. If I see getting the bits by modulo operator I will not recognize what is happening. Honestly  Roll Eyes


RE: & vs % - Skaperen - Nov-30-2017

try to understand base85 encoding,  you have to use % for that.  it's not bits.  i implement base85 about 3 decades ago in assembler and since then, also in C.  i don't need to implement it in Python as long as i use python3 since it already exists.