简体   繁体   English

如何在Python中将32b(四个字符)从int值转换为ASCII字符串

[英]How do I convert 32b (four characters) from an int value to an ASCII string in python

Hi I have a 32b value that I need to easily truncate in to it's four bytes, convert each byte to ASCII and combine them to a four letter string. 嗨,我有一个32b值,我需要轻松地将其截断为四个字节,将每个字节转换为ASCII,然后将它们组合成四个字母的字符串。 And I also need the reverse process. 我还需要相反的过程。 I have been able to do this in one direction in the following ugly way: 我已经能够通过以下几种方式在一个方向上做到这一点:

## the variable "binword" is a 32 bit value read directly from an MCU, where each byte is an 
## ASCII character

char0 = (binword & 0xFF000000) >> 24
char1 = (binword & 0xFF0000) >> 16
char2 = (binword & 0xFF00) >> 8
char3 = (binword & 0xFF)

fourLetterWord = str(unichr(char0))+str(unichr(char1))+str(unichr(char2))+str(unichr(char3))

Now, I find this method really un-elegant and time consuming, so the question is how do I do this better? 现在,我发现这种方法确实很繁琐且费时,所以问题是如何更好地做到这一点? And, I guess the more important question, how do I convert the other way? 而且,我猜更重要的问题是,如何以其他方式转换?

You should use the struct module's pack and unpack calls for these convertions 您应该使用struct模块的packunpack调用进行这些转换

number = 32424234

import struct
result = struct.pack("I", number)

and back: 然后回来:

 number = struct.unpack("I", result)[0]

Please, refer to the official docs on the struct module for the struct-string syntax, and markers to ensure endiannes, and number size. 请参考struct模块上的官方文档,以获取struct-string语法和标记以确保尾数和数字大小。 https://docs.python.org/2/library/struct.html https://docs.python.org/2/library/struct.html

On a side note - this is by no way "ASCII" - it is a bytestring. 附带说明-这绝不是“ ASCII”-它是一个字节串。 ASCII refers to a particular text encoding with codes on the 32-127 numeric range. ASCII是指一种特定的文本编码,其编码在32-127的数字范围内。 The point is that you should not think on bytestrings as text, if you need a stream of bytes - and much less think of "ASCII" as an alias for text strings - as it can represent less than 1% of textual characters existing in the World. 关键是,如果您需要字节流,则不应该将字节字符串视为文本-而不是将“ ASCII”作为文本字符串的别名-因为它可以表示少于1%的文本字符世界。

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

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