Binary numbers in Python

前端 未结 9 2086
孤独总比滥情好
孤独总比滥情好 2020-12-04 11:14

How can I add, subtract, and compare binary numbers in Python without converting to decimal?

相关标签:
9条回答
  • 2020-12-04 11:29

    I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.

    0 讨论(0)
  • 2020-12-04 11:30

    If you're talking about bitwise operators, then you're after:

    ~ Not
    ^ XOR
    | Or
    & And
    

    Otherwise, binary numbers work exactly the same as decimal numbers, because numbers are numbers, no matter how you look at them. The only difference between decimal and binary is how we represent that data when we are looking at it.

    0 讨论(0)
  • 2020-12-04 11:34

    You can convert between a string representation of the binary using bin() and int()

    >>> bin(88)
    '0b1011000'
    >>> int('0b1011000', 2)
    88
    >>> 
    
    >>> a=int('01100000', 2)
    >>> b=int('00100110', 2)
    >>> bin(a & b)
    '0b100000'
    >>> bin(a | b)
    '0b1100110'
    >>> bin(a ^ b)
    '0b1000110'
    
    0 讨论(0)
  • 2020-12-04 11:34

    Not sure if helpful, but I leave my solution here:

    class Solution:
        # @param A : string
        # @param B : string
        # @return a strings
        def addBinary(self, A, B):
            num1 = bin(int(A, 2))
            num2 = bin(int(B, 2))
            bin_str = bin(int(num1, 2)+int(num2, 2))
            b_index = bin_str.index('b')
            return bin_str[b_index+1:]
    
    s = Solution()
    print(s.addBinary("11", "100"))
    
    0 讨论(0)
  • 2020-12-04 11:45

    x = x + 1 print(x) a = x + 5 print(a)

    0 讨论(0)
  • 2020-12-04 11:46

    I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in. The fact that your python interpreter may store things as binary internally doesn't affect how you work with it - if you have an integer type, just use +, -, etc.

    If you have strings of binary digits, you'll have to either write your own implementation or convert them using the int(binaryString, 2) function.

    0 讨论(0)
提交回复
热议问题