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.
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
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.
We get this output :
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
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:
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:
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.