Python generally supports integers, fractional values and
complex numbers and we have data types for them like int for integers, float
for fractional values, and complex for complex numbers, we can understand that
but if our computer wants to perform certain operations on bits or some other
operations then we need to convert them into some number systems like binary,
octal, hexadecimal. These are the three different number systems.
Number conversions are used in programming languages because
we cannot directly use some operators like bit-wise operators, we need to
convert decimals into binary and sometimes we need to convert binary format of
a number to decimal, so we use number conversions there
Actually, number conversions are done on 4 types
1.
Decimal
2.
Binary
3.
Octal
4.
Hexadecimal
1. Decimal to binary:
Binary
– which means 2, we can only use 2 digits 0 and 1 so we call them as binary
digits nothing but bits.
So how to convert a number from decimal to binary
Ex: convert 25 to binary
0b011001
Divide
the given decimal by 2 and write down remainder aside and again do the division
and again write down the remainder, keep on doing this until u get a number
which is less than 2.
So when we
do the division 25 divided by 2 it gives us 12 as quotient and 1 as remainder ,
again when we divide 12 by 2 we get 6 as quotient 0 as remainder and again divide 6 by 2 we get
3 as quotient and 0 as remainder and again divide 3 by 2 we get 1 as remainder
and 1 as quotient so quotient value became 1 which means it is less than 1 so
we will stop the division , now from bottom
write remainders one by one and
till top number (bottom to top )
We will get like this 11001and add a zero before 1 then we
will get output as 011001 this is the binary number of decimal numbers 25
**** we also have
an easy method to convert decimal into binary because we can’t do this all the
time so computer will do this conversion for us, we just need to write a small syntax
for decimal to binary conversion that is
Syntax: bin(25) //bin()
function gives us the binary format
0b011001
Where here we put ‘zero’,b, so that it represents that the
given number is binary number.
2. Binary to decimal conversion:
If
you want to convert a binary number to decimal number then you need to multiply
every digit of the binary number with 2x where (x=0,1,2,3,4………)
And add all of them, I know u r a bit
confused with this. let’s just see an example
0b011001
0 1
1 0 0
1
25 24 23
22 21 20
Now we need to multiply with each number and add all of them
like this
(0*32) + (1*16) + (1*8) + (0*4) + (0*2) +
(1*1) where
20 = 1
= 0 + 16
+ 8 + 0 + 0 + 1
= 25
So, we got the output but this is also a long process so we will
use the binary number in the IDE or IDLE
Then it will convert the given binary number and gives us
the output in decimal number like this
Example: 0b011001
25
Here we put ‘zero ‘b (0b), so that...Continuation
Comments
Post a Comment