binascii.b2a vs ord()

Chris Angelico rosuav at gmail.com
Sun Jan 10 15:29:57 EST 2021


On Mon, Jan 11, 2021 at 7:09 AM Bischoop <Bischoop at vimart.net> wrote:
>
> On 2021-01-10, Chris Angelico <rosuav at gmail.com> wrote:
> >
> > Trace it through, step by step. You have a series of ASCII values,
> > represented in binary, and then you call int() on each of them. What
> > sort of numbers will you get?
> >
>
> I'm kinda lost here about what sort of numbers I get, its class 'int'.

Yep. Here, let me walk through one of the examples.

text2 = 'This is a string'
res = ' '.join(format(ord(i), 'b') for i in text2)

The first character is 'T', and ord('T') is 84. Formatting that in
binary gives '1010100'.

c = ' '.join(chr(int(val)) for val in res.split(' '))

You then convert the string '1010100' into an integer. That doesn't
give you the integer 84; it gives you the integer 1010100 (a bit over
a million).

Then you call chr() on that, which gives you the character with the
ordinal of 1,010,100 - or in hex, U+F69B4. That's not a well-defined
character (it's actually in a private-use area), so it displays as a
little box.

To undo the conversion from integer to binary, you have to interpret
the digits as binary. You can do that with int('1010100', base=2),
which will give back the integer 84.

Hope that helps!

ChrisA


More information about the Python-list mailing list