Binary numbers in Python Binary numbers in Python python python

Binary numbers in Python


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'


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.


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.