Create integer variable by assigning binary value in Python
Given a binary value and our task is to create integer variables and assign values in binary format. To assign value in binary format to a variable, we use the 0b suffix. It tells the compiler that the value (suffixed with 0b) is a binary value and assigns it to the variable.
Input: Var = 0b1010 Output: 10 Input: Var = 0b11001 Output: 25
Note: To print value in binary format, we use bin() function.
Example 1: Simple demonstration of binary and decimal format
Python3
num = 10 # print num in decimal and binary format print ( "num (decimal) : " , num) print ( "num (binary ) : " , bin (num)) |
Output:
num (decimal) : 10 num (binary ) : 0b1010
Example 2: Integer variable by assigning a binary value.
Python3
# Python code to create variable # by assigning binary value a = 0b1010 b = 0b11001 #printing the values in decimal form print ( "Value of a is: " , a) print ( "Value of b is: " , b) #printing the values again in binary form print ( "Value of a in binary form" , bin (a)) print ( "Value of b in binary form" , bin (b)) |
Output:
Value of a is: 10 Value of b is: 25 Value of a in binary form 0b1010 Value of b in binary form 0b11001
As mentioned above that we use the 0b suffix. , It tells the compiler that the value (suffixed with 0b) is a binary value and assigns it to the variable. So printing the binary form using bin() function 0b is also printed it just tells that represented number is in binary form. If we have printed these in hexadecimal form instead of “0b” “0x” would have been printed which is used to tell that number is represented in hexadecimal form.
Please Login to comment...