-1

When converting a number in binary in Python what you get is the following:

b = bin(77)
print(b)  # 0b1001101

When I was expecting 01001101. I am guessing that the b is there to let Python know that this is a binary number and not some integer. And that is ok within Python but what is considered safe practise here if you want to communicate with the outside world? This might be a silly example but online converters for instance do not recognise the above binary.

Would simply removing b always do the trick? Because I seem to be running into problems trying to code the Ascii85 encoder/decoder where concatenations of binary numbers take place. You can take a look at this example here.

My code is this case produces the following:

ch = 'Man '
list_ = [ord(x) for x in ch]  # [77, 97, 110, 32]
binary_repr = ''.join(bin(x) for x in list_)  # 0b10011010b11000010b11011100b100000
# When it should be                                01001101011000010110111000100000

Notice that simply replacing the b with nothing doesn't quite cut it here. This is probably some dumm mistake but can someone clear things up for me?

4
  • no, trimming two first characters will do the trick. Commented Jan 13, 2017 at 18:25
  • @ŁukaszRogalski but trimming the first 2 characters would result in 7 digits. How can that be? Commented Jan 13, 2017 at 18:34
  • 1
    @Ev.Kounis bin doesn't care about bytes, it just produces the shortest bitstring that represents the number. bin(1) -> 0b1 Some history of 0b Commented Jan 13, 2017 at 18:38
  • @PatrickHaugh I see. Thank all! Commented Jan 13, 2017 at 18:46

2 Answers 2

4
>>> format(b, '08b') 

Where b is your number and '08b' is the number of bit you want to use representing your number, if the parameter is #08b instead of 08b, you get the 0b in front of the number.

use format in every further operation and you should be good!

Sign up to request clarification or add additional context in comments.

3 Comments

or: print "{0:b}".format(77)
@alfasin I like it better that way too.
You are right, I forgot about that, just answered the first solution that came through my mind, it's been a long time since I last used phyton tbh
0

Doesn't

str(b)[2:] 

do the job?

But you'll maybe better do:

"{0:b}".format(77)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.