0

In a question I should deal with long inputs given as binaries. Like

"1000101011111101010100100101010101010101"

I am required to use the bitwise opertator OR | in this question. I have researched the use of this operator and it seems to work on regular integers not binaries. So I call int(thing, 2) on it. After that, I use the bitwise operator. However something troubles me. Isn't the python interpreter changes it back to binary again to apply Bitwise OR on it ? So isn't it seems like a repeated step ?

Is there no other way to directly use this string, maybe an iteration over all the letters is a better approach ? There is also another problem that about integer precision. Because sometimes the input is larger than 500 characters so I can't store it as an integer.

I tried something like this, Imagine a and b are two binary strings.

for comparison in zip(a, b):
    if any(comparison):
       # Do stuff if OR gives 1

This is proven to be very slow indeed. Please enlighten me.

Thanks in advance.

Max Paython
  • 1,595
  • 2
  • 13
  • 25
  • There is no step like "back to binary". Integers (and all numbers) are already stored in binary. So the answer is no, there is no additional step performed. – Selcuk Apr 18 '16 at 07:30
  • Fascinatingly simple indeed. However, isn't using the string directly(if a method exists) should be faster ? – Max Paython Apr 18 '16 at 07:32
  • No, because CPUs have dedicated operators for bitwise operations on numbers. – Selcuk Apr 18 '16 at 07:34
  • So should I prefer bitwise operations anywhere I can ? Because it is faster than integer operations ? – Max Paython Apr 18 '16 at 07:36
  • Note: "binary string" may have a different meaning (not "01"-string). Related: [Convert a text string to bits and back](http://stackoverflow.com/q/7396849/4279), [Fastest Bitwise XOR on Data Buffers](http://stackoverflow.com/q/2119761/4279). – jfs Apr 18 '16 at 10:00

1 Answers1

2

Firstly definitely use int(binary_string, 2) any other method will take longer. (although the for loop using zip and any is quite clever, however not optimal)

Python interpreter will not change your number back to binary as the computer already stores the number as binary in memory, it will use the CPU instruction for OR on the 2 numbers without converting them first. No repeated step.

linzwatt
  • 117
  • 6
  • Thank you and the commenters, you've been quite helpful :) – Max Paython Apr 18 '16 at 07:39
  • @MaxPythone: integers in Python have infinite precision. A single CPU instruction operates on finite numbers (e.g., 64-bit integers). How bitwise operations are implemented depends on Python implementation (e.g., CPython may use 30-bit digits). Though (in the end) CPU may execute `OR` instructions with some numbers. `gmpy2` integer arithmetic might be faster on large numbers (hundreds of digits). – jfs Apr 18 '16 at 10:00