Unpack IS vector or single byte

hi Digi’ers,

can anyone suggest how to unpack 1 byte and convert it to hex value in a single operation?
currently used code:

[i]
state = zigbee.ddo_get_param(DEST, ‘IS’,0.1)
sta = struct.unpack(‘=B’, state[5])
sta = ‘%s’ %(sta)
if sta == ‘15’:
__inp = “0000”


[/i]

many other tries gives me unpack str size does not match format error.

Simon

I am confused by the code at present… or, more correctly, I am confused by what you are trying to do.

The struct.unpack call returns a tuple (even a 1-tuple). All of the following should work (look carefully at comma placement):

sta_tuple = struct.unpack(‘=B’, state[5])
sta = sta_tuple[0]

sta = struct.unpack(‘=B’, state[5])[0]

sta, = struct.unpack(‘=B’, state[5])

Note also that the ‘=’ is not strictly required in our environment before a ‘B’, as there can be no endian confusion on our single byte values.

Once the integral value is in “sta”, you can just compare the integral value. I’m not sure what you mean by it needing to be converted to hex? Examples:

if sta == 123: print “123”
elif sta == 0x24: print “0x24”

You could also use:
bin = ord(state[5])

I wouldn’t use struct for ‘bytes’ as it seems overkill - struct is wonderful for rebuilding multi-byte int/longs/floats or for parsing several values in 1 shot.

But the old BASIC-ish chr() and ord() functions work well for byte-by-byte operations.

hi 52637p,

thanks for reply. i wasn’t aware of the tuple returned.
anyways, result is decimal again (15). i’d like to see ‘1111’ in the output. or at least 0xF. imagine 1 Byte of binary combination if…then…else clause.

simon

SOLVED.

sta = struct.unpack(‘=B’, state[5])[0]
sta = hex(sta)[2:]

result when state[5]=15 returns f

and hex->binary conversion i only managed to process through dictionary

There is no convenient Python 2.4.3 built-in function to express a number in binary form, that I am aware of. It is not a difficult conversion, of course.

Your line “sta=hex(sta)[2:]” could be expressed with the following string expression, if you need an exactly two digit hex string:

sta=“%02x” % sta

The one-liner, of course, is thus:

sta = “%02x” % struct.unpack(‘B’, state[5])[0]

Lots of options, as usual in Python!