Binary number representation python

Python Course #4: Introduction to Binary Numbers (Converting Decimal to Binary)

After you have learned about Boolean algebra in Python Course #3: Introduction to Boolean Algebra it is time to talk about the binary system and binary numbers based on Boolean algebra. Everything stored on your computer is stored in a binary representation. When you plan on working with embedded systems like Arduino or Raspberry Pi, understanding binary numbers is crucial to making your projects successful.

Continuous vs. Discrete

The storage of a computer, be it a hard drive (HDD), solid-state drive (SSD) or memory (RAM), is fundamentally built out of tiny little cells that store an electric or magnetic charge. No charge in such a cell usually represents a 0 (or false when thinking back at Boolean algebra), and when a charge is present, it is interpreted as 1 (or true). Those ones and zeros are called bits.

RAM Bits

But how can those arrays of ones and zeros be used to store complex information? Before answering this, it is essential to talk about the difference between continuous and discrete data.

The classic physics we perceive in our daily life is continuous. Think about a car with a constant acceleration \(a\), the velocity of the car is described as a function:

whereas \(v_0\) is the initial velocity. And the distance \(x\) traveled over time by this car is defined as:

When looking at a plot depicting the car’s motion, you can see that all three plots are “smooth,” meaning that there are no gaps in the graphs and that there are no sharp points.

Car Accelerated Motion Continous

When you want to accelerate your car to a certain velocity, you have to start from 0 and go through all values in between. There is no way to accelerate an object from 0 m/s to 10 m/s in an instant. This property is called continouos (there is actually a mathematical definition but this rough description sufices for the point I want to make).

Now think about how you would draw such a plot by hand when you only got a calculator, a piece of paper, and a pencil? You would most likely enter different values for \(t\) and draw markers for every point in your plot:

Car Accelerated Motion Discrete

This is called discrete. Because there are only values defined for specific values of \(t\), everything stored in a computer is discrete because it is composed of arrays of ones and zeros.

Representing a Number with only 1 and 0

All the numbers you interact with, for instance, on your bank account, the speed of a car at a fixed point in time, or the number of your friends, are decimal. And decimal means those numbers are base 10 because every digit from left to right represents a range that is 10 times greater than the number before. Take, for example, the number 2345 it is composed out of:

Читайте также:  Заполнить массив java элементами строки

Going from right to left, a zero is added to the end of every number. This adding of zeros can also be expressed as \(10^x\) where \(x\) is the digit’s position starting at 0 from the left. Now you can express 2345 like this (it is important to remember that \(y^0 = 1\)):

\[2\cdot 10^3 + 3\cdot 10^2 + 4\cdot 10^1 + 5\cdot 10^0 = 2345\]

In front of every \(10^x\) you can place one of the ten digits 0-9. So every decimal number that has \(n\) digits can be expressed as:

But what do you do when you only have 0 and 1? You build a number system of base 2, also called binary, where every digit of a number represents a number from the series 0, 1, 2, 4, 8, 16, 32, 64, etc. that are all results of \(2^x\). So if you want to represent the decimal number 23 in binary, you take the sum of \(1\cdot 16\), \(0\cdot 8\), \(1\cdot 4\), \(1\cdot 2\), and \(1\cdot 1\):

\[1\cdot 16 + 0\cdot 8 + 1\cdot 4 + 1\cdot 2 + 1\cdot 1 = 1\cdot 2^4 + 0\cdot 2^3 + 1\cdot 2^2 + 1\cdot 2^1 + 1\cdot 2^0= 23\]

the 1 and 0 in front of the \(2^x\) are the digits for the binary representation of 23:

When working with numbers from different number systems, it can be confusing what number is from which system. You can indicate the number system by adding a small subscript number at the end that represents the base:

With this representation, you can store any number as strings of 1 and 0 on your computer.

How to Converting Decimal Numbers into Binary Numbers?

To convert a number represented in decimal to binary, you can use the following Python print(. ) statement with a format string (indicated by the f in front of the first » ):

The x enclosed in braces < >means that the value of x should be printed as part of the string between quotes. The b after the colon tells Python to print x as a binary number. But how do you convert a decimal number using only pen and paper? Let’s use example 23 again. For the conversion, you have to divide 23 by 2 with the remainder until the result of the division is 0. And while you divide, keep track of the remainder in every step:

\[\begin \frac &= 11 & \quad R:1\\ \frac &= 5 & \quad R:1\\ \frac &= 2 & \quad R:1\\ \frac &= 1 & \quad R:0\\ \frac &= 0 & \quad R:1\\ \end\]

When you reach the division result 0, write down the remainders from bottom to top. Those are the digits of the binary representation: \(10111\). Try it out yourself with 2345 and check your result in Python.

How to Convert Binary Number into Decimal?

When you get a binary number and want to know its decimal representation, you can also use Python. Enter your binary number with 0b in front and then print it:

Читайте также:  Python beginners book pdf

To convert a binary number into a decimal number by hand, you can make use of the general mathematical representation of binary numbers:

Take every digit and multiply it with corresponding \(2^i\) and sum the up. Remember that the last bit on the left in on postition 0 (also called the least significant bit or LSB). Lets take 101011 and find out it’s decimal representation:

\[1\cdot2^5 + 0\cdot 2^4 + 1\cdot 2^3 + 0\cdot 2^2 + 1\cdot 2^1 + 1\cdot 2^0 = 32 + 0 + 8 + 0 + 2 + 1 = 43\]

Converting binary numbers into the decimal system concludes this article. You’ve learned that computers store values only in the form of ones and zeros, the difference between continuous and discrete data, and that computers can only store discrete data. Additionally, you’ve learned how to convert a decimal number into a binary number and the other way around. I encourage you to try out the conversion on your own with the number:

If you have any questions about this article, feel free to join our Discord community to ask them over there.

Источник

Binary representation python – Python Program to Print Binary Representation of a Number

Program to Print Binary Representation of a Number

Get binary representation python: Binary (or base-2) is a numeral system with only two digits — 0 and 1. Computers use binary to store data and execute calculations, which means they only use zeros and ones. In Boolean logic, a single binary digit can only represent True (1) or False (0). Any integer, in fact, can be represented in binary.

Given a decimal number the task is to convert the given decimal to binary

The binary representation of the given number 200 : 11001000
The binary representation of the given number 1: 1
The binary representation of the given number 32 : 100000

Python Program to Print Binary Representation of a Number

Binary representation python: There are several ways to print the binary representation of a given decimal number some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using recursive function

Binary representation python: To find a binary equivalent, divide the decimal number recursively by the value 2 until the decimal number hits zero. The remaining must be noted after each division. The binary equivalent of the decimal number is obtained by reversing the remaining values.

  1. Get the given decimal number from the user or static input.
  2. If the input is larger than zero, divide it by 2 and record the remainder.
  3. Step 2 should be repeated until the decimal number reaches zero.
  4. The residual values should be printed.
  5. End of program

Below is the implementation:

def decitoBin(numb): # checking if the given number is greater than 1 if numb > 1: # if it is greater than 1 then use recursive approach by dividing number by 2 decitoBin(numb // 2) # printing the binary representation of the given number print(numb % 2, end='') # Driver code given_numb = 200 # passing given number to decitoBin function to print binary representation of the givennumb print("The binary representation of the given number", given_numb, " : ") decitoBin(given_numb)
The binary representation of the given number 200 : 11001000

Method #2:Using while loop

  • First we take a empty string say binstr.
  • We use while loop .
  • We will iterate till the number is greater than 0 (Condition of while statement)
  • We will get the last check bit whether it is set bit or not using % operator
  • Convert the set bit to string using str() function
  • Concatenate this bit(can be 1 or 0 ) to the binstr.
  • Reverse this binstr using slicing
  • Print the binary representation of the given number that is print binstr.
Читайте также:  Connection php mysql html

Below is the implementation:

def decitoBin(numb): # checking if the given number is greater than 1 if numb > 1: # taking a empty string binastring = "" # looping till number greater than 0 using while loop while(numb > 0): # We will get the last check bit whether it is set bit or not using % operator checkbit = numb % 2 # converting this checkbit to string using str() function checkbit = str(checkbit) # Concatenate this bit(can be 1 or 0 ) to the binstr. binastring = binastring+checkbit # divide the number by 2 numb = numb//2 # reverse the binary string binastring = binastring[::-1] # return the resultant binary string return binastring # Driver code given_numb = 200 # passing given number to decitoBin function to print binary representation of the givennumb print("The binary representation of the given number", given_numb, " : ") print(decitoBin(given_numb))
The binary representation of the given number 200 : 11001000

Method #3:Using Built in Python function bin()

  • We will use bin() function to convert the given decimal number to binary representation.
  • It will return the result in the form of 0bXXXXXXXXX where XXXXXXXX is binary representation.
  • To remove that 0b characters from the string we use two methods
  • Print the resultant binary representation.

i)Using replace function

We will replace the 0b in the binary string with empty string.

Below is the implementation:

def decitoBin(numb): # converting it to binary representation using bin() function binNumb = bin(numb) # replacing '0b' using replace function and replacing it with empty string binNumb = binNumb.replace('0b', '') # return the binary representation of the given number return binNumb # Driver code given_numb = 200 # passing given number to decitoBin function to print binary representation of the givennumb print("The binary representation of the given number", given_numb, " : ") print(decitoBin(given_numb))
The binary representation of the given number 200 : 11001000

The binary representation of the given decimal number will be printed.

ii)Using slicing

We will slice from 2 index to last index of the result returned by binary string

Below is the implementation:

def decitoBin(numb): # converting it to binary representation using bin() function binNumb = bin(numb) # We will slice from 2 index to last index of the result returned by binary string binNumb = binNumb[2:] # return the binary representation of the given number return binNumb # Driver code given_numb = 200 # passing given number to decitoBin function to print binary representation of the givennumb print("The binary representation of the given number", given_numb, " : ") print(decitoBin(given_numb))
The binary representation of the given number 200 : 11001000

The binary representation of the given decimal number will be printed.

Related Programs:

Источник

Оцените статью