binary in python code example
Example 1: convert int to binary python
def decimalToBinary(n):
return bin(n).replace("0b", "")
if __name__ == '__main__':
print(decimalToBinary(8))
print(decimalToBinary(18))
print(decimalToBinary(7))
Output:
1000
1001
Example 2: binary operation python
x << y
"left shifted x by y places"
x >> y
"right shift x by y places"
x & y
"bitwise and"
x | y
"bitwise or".
~ x
"Complement of x"
x ^ y
"bitwise exclusive or"
Example 3: binary to decimal in python
int(binaryString, 2)
Example 4: python binary
num = 10
bin(num)
Example 5: binary representation python
>>> 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'
Example 6: decimal to binary in python
a = 10
bnr = bin(a).replace('0b','')
x = bnr[::-1]
while len(x) < 8:
x += '0'
bnr = x[::-1]
print(bnr)