469,282 Members | 1,751 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,282 developers. It's quick & easy.

Writing a Python program that demonstrates operations of bitwise operators using binary digits. Without using the bitwise operators

Symbol Operation Operation
& and Sets result bit to 1 if both corresponding bits are 1. E.g. 1010 & 1100 is 1000
l or Sets result bit to 1 if one of the two corresponding bits is 1. E.g 1010 & 1100 is 1110
^ xor Sets result bit to 1 only if one of the corresponding bits is 1. E.g. 1010 & 1100 is 0110

def main():
# input
binary1, operator, binary2 = str(input('Enter binary expression: ')).split(' ') # Enter our binary expression

output = '' # Output initialized to empty string
output = binary1 + binary2 # Concatenate strings to it, not numbers.

for i in range(0, len(binary1)):
if operator == '&':
binary1[i] != binary2[i]
if binary1[i]==1 and binary2[i]==1:
output = chr(output + str(1)) # Appended 1 is converted to string
else:
output = output + str(0) # Append 0 when the condition is not true
elif operator == '|':
if binary1[i]==1 or binary2[i]==1:
output = chr(output + str(1)) # Appended 1 is converted to string
else:
output = output + str(0) # Append 0 when the condition is not true
elif operator == '^':
if not binary1[i]==0 and binary2[i]==1:
output = chr(output + str(1)) # Appended 1 is converted to string
else:
output = output + 0 # Append 0 when the condition is not true
elif operator == '~':
if binary1[i]==1 and not binary2[i]==0:
output = chr(output + str(1)) # Appended 1 is converted to string
else:
output = output + 0 # Append 0 when the condition is not true

print(output) # This is correct

# output

main()

Current Result:
Enter binary expression: 1110 & 1000
Result: 111010000000

Expected Result
Enter binary expression: 1110 & 1000
Result: 1000

Hi all, the error in my code is that when I input a binary expression 1110 & 1000,
I get 101011110000. But I am supposed to get the result 1000.
Could someone help me with this ?
Aug 18 '21 #1
0 1027

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by sandy_pt_in | last post: by
12 posts views Thread by sandy_pt_in | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.