How to Convert Number to Binary In Python

which is also known as the binary equivalent function so what this does is return to a string that represents any integer number as a binary number starting with the letter 0b.

How to Convert Number to Binary In Python

We are going to be talking about the bin function which is also known as the binary equivalent function so what this does is return to a string that represents any integer number as a binary number starting with the letter 0b.

I will show you what I mean by that essentially if I print

Num=23

Print(bin(num))

The output:

Ob10111

out bin num this is going to turn 23 into a binary number when I print this you see we get : 0 B 1 0 1 1 1

The 0b just stands for this is a binary equivalent and actually the type that's returned by this is a string and not some kind of number there's no specific type in Python for a binary number it just gives you a string.

Print(type(bin(num)))

We get this output :

<class ‘str’>

This is important because if we try to do something like turn our binary number back into an integer I'll show you what happens so notice this is our binary number now I'm just going to remove the 0b from it and the way that you can do that since this is a string is just by indexing and getting from index 2 onward which means we're going to start here and go to the end of the string

 

Print(bin(num)[2:])

so, when I do that you see we get:

 1 0 1 1 1

Let's just convert this into an integer by putting int and let's see what we get:

print(int(bin(num)[2:])

In theory you think we should get 23 back because you are going to convert from a binary but what we really end up getting is the same thing with the actual:

10111

Which obviously was not the same number that we converted into binary so just be aware of that once you go into binary you cannot go backwards unless you have some like weird conversion method and you've written something to do that but anyways that's kind of how bin works.

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0