简体   繁体   中英

python Long to Byte Array of 2 byte using struct

I am converting long or int to bytearray in python using struct

ba = struct.pack('H',12)

output : '\\x0c\\x00' length 2 bytes

but if i convert ba = struct.pack('H',12345)

output : '90' i need to encode to hex for desired out put ba.encode('hex') in this case output is output : 3930 and length is 4

why this is happening, it should give 2 byte result without encoding ?

my usecase is i need to convert long to bytearray of desired bytearray size.

'90' is two bytes. The first byte is 0x39 and the second is 0x30.

>>> hex(12345)
'0x3039'

TL;DR: You are getting the correct result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM