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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ShawnYang
    New Member
    • Aug 2021
    • 1

    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('Ente r 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 ?
Working...