views:

95

answers:

3

Hi, maybe this is a noob question, but I'm receiving some data over TCP and when I look at the string I get the following:

\x00\r\xeb\x00\x00\x00\x00\x01t\x00

What is that \r character, and what does the t in \x01t mean?

I've tried Googling, but I'm not sure what to Google for...

thanks.

+9  A: 

\r is a carriage return (0x0d), the t is a t.

Blrfl
If that's the case, why isn't it given simply as 0x0d?
nieldw
Because there's a standard escape, `\r`, designated for it. Search for "C character escapes" and you'll find a table of how they're represented.
Blrfl
@nieldw Python represents `bytes` objects as strings of hex values identifying each byte, except when the hex value is that of a printable/commonly used ASCII value.
Beau Martínez
Thanks @Beau Martinez, that makes it clear.
nieldw
+4  A: 

Viewing binary data in strings can sometimes be confusing, especially if they're long, but you can always convert it to some easier-to-read hex.

>>> data = '\x00\r\xeb\x00\x00\x00\x00\x01t\x00'
>>> ' '.join(["%02X" % ord(char) for char in data])
'00 0D EB 00 00 00 00 01 74 00'

Also, if you're just parsing the byte string into fields, just ignore the string and just go right to unpacking it with the struct module:

>>> import struct
>>> length, command, eggs, spam = struct.unpack('!BBi4s',data)
>>> #...whatever your fields really are
>>> print "len: %i\ncmd: %i\negg qty: %i\nspam flavor: '%s'" % (
...     length, command, eggs, spam)
len: 0
cmd: 13
egg qty: -352321536
spam flavor: ' ☺t '
Nick T
+2  A: 

When displaying data as a string, printable characters (such as 't' are displayed as characters, known control sequences are displayed as escapes, and other bytes are displayed in \x## form. Example:

>>> s='\x74\x0d\x99'
>>> s
't\r\x99'

You can dump a hexadecimal form with:

>>> import binascii
>>> binascii.hexlify(s)
'740d99'
Mark Tolonen