views:

668

answers:

4

Hi all!

Lets put it in parts.

I got a socket receiving data OK and i got it in the \x31\x31\x31 format.

I know that i can get the same number, ripping the \x with something like

for i in data: print hex(ord(i))

so i got 31 in each case.

But if I want to add 1 to the data (so it shall be "32 32 32")to send it as response, how can i get it in \x32\x32\x32 again?

Thanks in advance ;)

Rag!

+4  A: 

use the struct module

unpack and get the 3 values in abc

(a, b, c) = struct.unpack(">BBB", your_string)

then

a, b, c = a+1, b+1, c+1

and pack into the response

response = struct.pack(">BBB", a, b, c)

see the struct module in python documentation for more details

luc
A: 

The opposite of ord() would be chr().

So you could do this to add one to it:

newchar = chr(ord(i) + 1)

To use that in your example:

newdata = ''

for i in data:
   newdata += chr(ord(i) + 1)

print repr(newdata)

But if you really wanted to work in hex strings, you can use encode() and decode():

>>> 'test string'.encode('hex')
'7465737420737472696e67'
>>> '7465737420737472696e67'.decode('hex')
'test string'
Andre Miller
+3  A: 

The "\x31" is not a format but the text representation of the binary data. As you mention ord() will convert one byte of binary data into an int, so you can do maths on it.

To convert it back to binary data in a string, you can use chr() if it's on just one integer. If it's many, you can use the %c formatting character of a string:

>>> "Return value: %c%c%c" % (5,6,7)
'Return value: \x05\x06\x07'

However, a better way is probably to use struct.

>>> import struct
>>> foo, bar, kaka = struct.unpack("BBB", '\x06\x06\x06')
>>> struct.pack("BBB", foo, bar+1, kaka+5)
'\x06\x07\x0b'

You may even want to take a look at ctypes.

Lennart Regebro
A: 

OMG, what a fast answering! :D

I think that i was stuck on the ">B" parameter to struct, as i used "h" and that sample parameters (newbie on struct.pack talking!)

Tried the encode/decode thing but socket on the other side receive them as numbers, not the "\x" representation it wanted.

I really enjoy the simplicity of %c format, and will use that as temporal thing (i dont process so many data so have not reason to be ultraefficient atm :D) or the struct thing after playing with it a bit.

And in the example, to just play with one char at a time, find struct working too, usint ">B" only hehe.

Thanks to all.