czobrisky
czobrisky

Reputation: 175

How to convert string of ints of type unsigned char to an int in python

I have a socket connection from a C++ client connecting to a python server. The client is placing a Diffie-Hellman key in the message but when I view it it is garble due to being unsigned chars on the client side.

I've been able to do a raw dump using repr(key), and got the following:

\'V\x99\xf3\x0c\x1b\xc7]\x1f\xe4\nQ5$*\x88\x88Yg\xff{\xea\xe9e\xd8\xb32oD\xff
\xcfV\x84\x90xv,\x9dw\x1e(\x12\xfe\x9a\xb4,\x96%\xad;S\xb6\xa3\xf9\xb69\xfa\xec
\x1dl\x97\x1d\xd64/'

The key length should be 64. How do I go about converting this string to 64 ints that is the actual key?

Upvotes: 2

Views: 2183

Answers (1)

unwind
unwind

Reputation: 399713

You can use the nice struct module to unpack it. This will give you a tuple of 64 small integers (the B means "unsigned char"):

>>> print repr(data)
'V\x99\xf3\x0c\x1b\xc7]\x1f\xe4\nQ5$*\x88\x88Yg\xff{\xea\xe9e\xd8\xb32oD\xff\xcfV\x84\x90xv,\x9dw\x1e(\x12\xfe\x9a\xb4,\x96%\xad
;S\xb6\xa3\xf9\xb69\xfa\xec\x1dl\x97\x1d\xd64/'
>>> len(data)
64
>>> struct.unpack("64B", data)
(86, 153, 243, 12, 27, 199, 93, 31, 228, 10, 81, 53, 36, 42, 136, 136, 89, 103, 255, 123, 234, 233, 101, 216, 179, 50, 111, 68,
255, 207, 86, 132, 144, 120, 118, 44, 157, 119, 30, 40, 18, 254, 154, 180, 44, 150, 37, 173, 59, 83, 182, 163, 249, 182, 57, 250
, 236, 29, 108, 151, 29, 214, 52, 47)

Upvotes: 2

Related Questions