Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #46070

Re: Output from to_bytes

References <knstkh$74a$1@news.albasani.net>
Date 2013-05-26 23:26 +1000
Subject Re: Output from to_bytes
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2174.1369574797.3114.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, May 26, 2013 at 10:02 PM, Mok-Kong Shen
<mok-kong.shen@t-online.de> wrote:
> I don't understand why with the code:
>
>    for k in range(8,12,1):
>      print(k.to_bytes(2,byteorder='big'))
>
> one gets the following output:
>
>    b'\x00\x08'
>    b'\x00\t'
>    b'\x00\n'
>    b'\x00\x0b'
>
> I mean the 2nd and 3rd should be b'\x00\x09' and b'x00\x0a'.
> Anyway, how could I get the output in the forms I want?

They are. If you compare them, you'll find they're identical:

>>> b'\x00\t' == b'\x00\x09'
True
>>> b'\x00\n' == b'\x00\x0a'
True

It's just a representation issue. The repr() of a bytes tries to go
for the shorter representation \n rather than the more verbose \x0a.
(Though I'm not sure why it doesn't also shorten \x00 to \0 - maybe
the \0 notation isn't deemed Pythonic, even though it does work just
fine.) So what you want is a more fixed representation.

What you may find useful here is that iterating over the bytes object
produces integers:

>>> list(b'\0\t')
[0, 9]

So you might be able to do something like this:

>>> print(''.join(('\\x%02x'%x for x in b'\0\t')))
\x00\x09

Or, in your whole loop:

>>> for k in range(8,12,1):
	print(''.join(('\\x%02x'%x for x in k.to_bytes(2,byteorder='big'))))

\x00\x08
\x00\x09
\x00\x0a
\x00\x0b

Does that help?

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Output from to_bytes Mok-Kong Shen <mok-kong.shen@t-online.de> - 2013-05-26 14:02 +0200
  Re: Output from to_bytes Chris Angelico <rosuav@gmail.com> - 2013-05-26 23:26 +1000
  Re: Output from to_bytes Terry Jan Reedy <tjreedy@udel.edu> - 2013-05-26 16:45 -0400
  Re: Output from to_bytes Grant Edwards <invalid@invalid.invalid> - 2013-05-28 15:35 +0000
    Re: Output from to_bytes Mok-Kong Shen <mok-kong.shen@t-online.de> - 2013-06-02 21:09 +0200
      Re: Output from to_bytes Ned Batchelder <ned@nedbatchelder.com> - 2013-06-02 18:18 -0400

csiph-web