简体   繁体   English

python使用struct从2字节长到字节数组

[英]python Long to Byte Array of 2 byte using struct

I am converting long or int to bytearray in python using struct 我正在使用struct将long或int转换为python中的bytearray

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

output : '\\x0c\\x00' length 2 bytes 输出:'\\ x0c \\ x00'长度2个字节

but if i convert ba = struct.pack('H',12345) 但是如果我转换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 输出:“ 90”,我需要编码为十六进制以获得所需的输出ba.encode('hex'),在这种情况下,输出为:3930,长度为4

why this is happening, it should give 2 byte result without encoding ? 为什么会发生这种情况,它应该给出2字节的结果而不进行编码?

my usecase is i need to convert long to bytearray of desired bytearray size. 我的用例是我需要将long转换为所需的bytearray大小的bytearray。

'90' is two bytes. '90'是两个字节。 The first byte is 0x39 and the second is 0x30. 第一个字节为0x39,第二个字节为0x30。

>>> hex(12345)
'0x3039'

TL;DR: You are getting the correct result. TL; DR:您得到正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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