views:

185

answers:

3

In Python, I'm constantly using the following sequence to get an integer value from a byte buffer (in python this is a str).

I'm getting the buffer from the struct.unpack() routine. When I unpack a 'char' using

byte_buffer, = struct.unpack('c', raw_buffer)
int_value = int( byte_buffer.encode('hex'), 16 )

Is there a better way?

+5  A: 

The struct module is good at unpacking binary data.

int_value = struct.unpack('>I', byte_buffer)[0]
Ned Batchelder
Noah didn't specify that the number will always be from 0 to unsigned int.
Unknown
@Unknown: The code Noah pasted seems to do exactly that.
nosklo
@nosklo, no, the code he pasted accepts unbounded integers. Try int( ("a"*500).encode('hex'), 16 ) for proof.
Unknown
+2  A: 

Bounded to 1 byte – Noah Campbell 18 mins ago

The best way to do this then is to instantiate a struct unpacker.

from struct import Struct

unpacker = Struct("b")
unpacker.unpack("z")[0]

Note that you can change "b" to "B" if you want an unsigned byte. Also, endian format is not needed.

For anyone else who wants to know a method for unbounded integers, create a question, and tell me in the comments.

Unknown
Ahh...using the b vs. B returns an integer. (Flips to the python docs and realizes he needed to keep reading...)
Noah Campbell
+1  A: 

If we're talking about getting the integer value of a byte, then you want this:

ord(byte_buffer)

Can't understand why it isn't already suggested.

ΤΖΩΤΖΙΟΥ
Perhaps because struct is more likely to be the correct answer for other parts of his problem, if reading various pieces of data from a byte stream.
Kylotan
I was going to suggest this, but the asker didn't specify whether or not it would be signed or unsigned, so struct is the best option.
Unknown