简体   繁体   English

整数到字节而不在python中使用struct

[英]integer to byte without using struct in python

I need to use an embedded system running Python 1.5.2+ (!!!) with very few modules. 我需要使用运行Python 1.5.2+(!!!)且具有很少模块的嵌入式系统。 And there is no "struct" module usable... Here is the list of usable modules : 而且没有可用的“结构”模块...这是可用模块的列表:

marshal
imp
_main_
_builtin_
sys
md5
binascii

Yes that's it, no struct module... 是的就是这样,没有struct模块...

So, I need to create a 4 bytes representation of an unsigned short integer to send to serial... 因此,我需要创建一个4字节的无符号短整数表示形式以发送到串行...

With struct : 用struct:

date = day + month * 32 + (year - 2000) * 512
time = 100 * hour + minute
data = struct.pack(b'HH', date, time)

date on 2 bytes time on 2 bytes and everybody's happy... 2个字节的日期2个字节的时间,每个人都很高兴...

But without using 'struct' module, how can I do that? 但是,如果不使用“结构”模块,该怎么办?

You can do something like this: 您可以执行以下操作:

x = 0xabcd

packed_string = chr((x & 0xff00) >> 8) + chr(x & 0x00ff)

Here is a complete translation for you 这是给您的完整翻译

Before 之前

>>> import struct
>>> day = 1; month = 2; year = 2003
>>> hour = 4; minute = 5
>>> date = day + month * 32 + (year - 2000) * 512
>>> time = 100 * hour + minute
>>> data = struct.pack(b'HH', date, time)
>>> data
'A\x06\x95\x01'
>>> data.encode("hex")
'41069501'

And after 之后

>>> data2 = chr(date & 0xFF) + chr((date >> 8) & 0xFF) + chr(time & 0xFF) + chr((time >> 8) & 0xFF)
>>> data2
'A\x06\x95\x01'
>>> data2.encode("hex")
'41069501'
>>>

我能够通过将字节列表传递给bytes()来做到这一点:

data=bytes([date%256,date//256,time%256,time//256])

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

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