Domanda

I've got an array of short/int16s that i need to convert to a padded 16 bit-string(?). I've tried using struct:

struct.pack('>H', 545)

To which i get:

'\x02!'

Whereas I need something formatted as 16 bits.

Does anyone know how to do this? I'm rather confused and know next to nothing about the binary system.

Cheers

È stato utile?

Soluzione

That is 16 bits. '\x02' is 8 bits, and ! is the other 8.

Were you looking for '0000001000100001'? If so, you can do that with the format function:

>>> format(545, '016b')
'0000001000100001'

The 0 means "pad with zeros", the 16 means "show at least 16 digits", and the b means binary.

If you don't need the zero padding, you can just use bin:

>>> bin(545)
'0b1000100001'
>>> bin(545)[2:]
'1000100001'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top