Python | Binary numbers representation (assign, conversion, bitwise operations)

Binary numbers representation in Python: In this tutorial, we will learn how to work with binary numbers, assignment of binary numbers, binary numbers conversion, and various bitwise operations on binary numbers. By IncludeHelp Last updated : June 26, 2023

Assign binary value to the variable

To assign binary values to the variable, we use prefix 0b or 0B with the binary value.

Example

# assign number as binary 
# prefix 0b 
num = 0b111101
print "num: ", num

# prefix 0B 
num = 0B111101
print "num: ", num

Output

num:  61
num:  61

Convert a decimal value to binary

To convert a decimal value to the binary, we use bin() Method, which is an inbuilt method in the Python.

Example

Python program, that returns a binary value of given decimal value

num = 61
# print num in decimal and binary format 
print "num (decimal) : ", num
print "num (binary ) : ", bin (num)

Output

num (decimal) :  61
num (binary ) :  0b111101

Convert binary value to decimal

When, we print the binary value – there is no need to convert it; print prints the value in decimal format, like

print 0b111101 - its output will be 61.

Still, we can use int() method to convert it into decimal by defining base of the number system.

Example

# print by using binary value
print  0b111101
# print by converting to decimal
print int ('0b111101 ', 2)

Output

61
61

Bitwise OR (|) and AND (&) Operations

Here is the bitwise OR (|) and Bitwise AND (&) Operations:

Example

a = 0b111101
b = 0b000010

# print value in binary 
print "values in binary..."
print "a: ",bin (a)
print "b: ",bin (b)

# bitwise OR and AND operations
print "(a|b) : ", bin (a|b)
print "(a&b) : ", bin (a&b)

# print values in decimal 
print "values in decimal..."
print "a: ",a 
print "b: ",b 

# bitwise OR and AND operations 
print "(a|b) : ", int (bin (a|b),2)
print "(a&b) : ", int (bin (a&b),2)

Output

values in binary...
a:  0b111101
b:  0b10
(a|b) :  0b111111
(a&b) :  0b0
values in decimal...
a:  61
b:  2
(a|b) :  63
(a&b) :  0

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.