on-internet
← Community

Bitwise subtraction in Python

Stack Overflow ·

This is a follow-up to my question yesterday: CMS kindly provided this example of using bitwise operators to add two numbers in C: #include<stdio.h> int add(int x, int y) { int a, b; do { a = x & y; b = x ^ y; x = a << 1; y = b; } while (a); return b; } int main( void ){ printf( "6 + 3 = %d", add(6,3)); printf( "6 - 3 = %d", add(6,-3)); return 0; } It works great and I then ported it to Python as follows: def add(x, y): while True: a = x & y b = x ^ y x = a << 1 y = b if a == 0: break return b print "6 + 3 = %d" % add(6,3) print "6 - 3 = %d" % add(6,-3) They both work for addition and the C pr

Comments

Sign in or sign up to comment and upvote.

No comments yet.