Is there a better way than int (byte_buffer.encode ('hex'), 16)

In Python, I constantly use the following sequence to get an integer value from a byte buffer (in python, it's str).

I get a buffer from the struct.unpack () procedure. When I decompress 'char' using

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

Is there a better way?

+3
source share
3 answers

Limited to 1 byte - Noah Campbell 18 minutes ago

The best way to do this is to create an instance of the struct unpacker.

from struct import Struct

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

Please note that you can change “b” to “B” if you need an unsigned bike. In addition, endian format is not required.

, , .

+2

struct .

int_value = struct.unpack('>I', byte_buffer)[0]
+6

If we are talking about getting an integer byte value, then you want this:

ord(byte_buffer)

I can not understand why this has not yet been proposed.

+1
source

Source: https://habr.com/ru/post/1709253/


All Articles