Python What is a more efficient way to perform bitwise operations in Python?

  • Thread starter Thread starter Adyssa
  • Start date Start date
  • Tags Tags
    Operations Python
AI Thread Summary
The discussion centers on implementing bitwise operations in Python without using built-in operators. The initial focus is on creating a manual bitwise AND function. The provided implementation uses string manipulation to build the result, but the user seeks a more efficient method that utilizes integer types directly. A suggestion is made to use the divmod operator to handle the division and modulus operations simultaneously, which simplifies the process. The conversation evolves into sharing alternative implementations, including a divmod-based version and a manual mod and divide approach. Both methods aim to achieve the same result while avoiding string conversions, highlighting the importance of clarity and efficiency in coding practices.
Adyssa
Messages
202
Reaction score
3
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):

Code:
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

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?
 
Last edited:
Technology news on Phys.org


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 ...

attachment.php?attachmentid=54739&stc=1&d=1358249555.jpg
 

Attachments

  • phys - 13 01 15 boolean 01.jpg
    phys - 13 01 15 boolean 01.jpg
    33.2 KB · Views: 911


Thanks, that's nice and simple :) I can stare at problems forever and just not grok things properly sometimes! Here's some Python code:

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
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
Thread 'Project Documentation'
Trying to package up a small bank account manager project that I have been tempering on for a while. One that is certainly worth something to me. Although I have created methods to whip up quick documents with all fields and properties. I would like something better to reference in order to express the mechanical functions. It is unclear to me about any standardized format for code documentation that exists. I have tried object orientated diagrams with shapes to try and express the...
Back
Top