I'm playing around in Python at the moment, and I came across an exercise to perform bitwise operations manually (without the built in & | ^ ~ operators).(adsbygoogle = window.adsbygoogle || []).push({});

I understand the operations on paper, and I have a function here that performs them (& in this case, the others are similar):

I'd like some help modifying this implementation to use an integer type for the result instead of a string type which I then have to convert. I was trying to set the current result bit and then left shift (<<) but it didn't work when I only had 0 bits to work with because 0b0 == 0b00 == 0b0000000 so there's no significant 1 bit to shift. Is there a neater way do this?Code (Text):def bitwise_and(num1, num2):

result = "" # the result of the bitwise and operation

while num1 > 0 or num2 > 0:

# num % 2 != 0 implies a 1-bit in the lowest position

if num1 % 2 != 0 and num2 % 2 != 0:

result = "1" + result # both bits are 1, so 1 & 1 == 1, append 1 to result

else:

result = "0" + result# at least one 0 bit, 1 & 0 == 0, 0 & 0 == 0, append 0

num1 = num1 >> 1 # drop the last bit

num2 = num2 >> 1 # drop the last bit

return int(result,2) # return an int representation of the result binary string

**Physics Forums | Science Articles, Homework Help, Discussion**

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# [python] Bitwise Operations

Loading...

Similar Threads for python Bitwise Operations |
---|

Python for vector files |

Practicing Python and R at the same time |

Python (VPython) Can someone help me with my orbit simulator? |

Python Create a sign-out sheet in Python |

Python How can I run Python by getting values from Matlab |

**Physics Forums | Science Articles, Homework Help, Discussion**