|Jan14-13, 05:49 PM||#1|
[python] Bitwise Operations
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).
I understand the operations on paper, and I have a function here that performs them (& in this case, the others are similar):
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
|Jan15-13, 05:33 AM||#2|
I've not programmed in Python, however, ... Have you considered using the divmod operator, with the 'div' bit providing the shifted number and then multiplying the 'mod' bits together (then iterating until the 'div' bit of either number is 0). It seems to work in Mathcad ...
|Jan18-13, 04:31 AM||#3|
Thanks, that's nice and simple :) I can stare at problems forever and just not grok things properly sometimes! Here's some Python code:
#divmod version def divmod_and(x, y): z = 0 p = 1 while x or y: x, xd = divmod(x, 2) y, yd = divmod(y, 2) z = p * xd * yd + z p <<= 1 return z # manual mod and divide for clarity def bitwise_and(x, y): result = 0 power = 1 while x or y: bit = x % 2 * y % 2 # both bits on == 1 result = bit * power + result x /= 2 y /= 2 power <<= 1 return result
|Similar Threads for: [python] Bitwise Operations|
|Simulating bitwise AND operator||Engineering, Comp Sci, & Technology Homework||4|
|Bitwise AND operation backwards||Engineering, Comp Sci, & Technology Homework||3|
|Bitwise operations in Macysma derived Computer Algebra Systems?||Programming & Comp Sci||1|
|bit shifting and bitwise operators||Engineering, Comp Sci, & Technology Homework||1|
|Bitwise Operation||Electrical Engineering||0|