简体   繁体   English

在 Python 中声明单字节变量

[英]Declaring a single byte variable in Python

How do we declare a single byte variable in Python?我们如何在 Python 中声明一个单字节变量? I would like to achieve the following result represented in C:我想实现以下用 C 表示的结果:

unsigned char = 0xFF;

I would like to know if it is possible to declare an 8-bit variable in Python.我想知道是否可以在 Python 中声明一个 8 位变量。

Python doesn't differentiate between characters and strings the way C does, nor does it care about int bit widths. Python 不像 C 那样区分字符和字符串,也不关心int位宽。 For a single byte, you basically have three choices:对于单个字节,您基本上有三个选择:

  1. A length 1 bytes (or bytearray ) object mychar = b'\\xff' (or mychar = bytearray(b'\\xff') )长度为 1 bytes (或bytearray )的对象mychar = b'\\xff' (或mychar = bytearray(b'\\xff')
  2. An int that you don't assign values outside range(256) (or use masking to trim overflow): mychar = 0xff一个int ,你不分配range(256)之外的range(256) (或使用掩码来修剪溢出): mychar = 0xff
  3. A ctypes type, eg mychar = ctypes.c_ubyte(0xff)ctypes类型,例如mychar = ctypes.c_ubyte(0xff)

The final option is largely for dealing with C functions through ctypes , it's otherwise slow/not Pythonic.最后一个选项主要是通过ctypes处理 C 函数,否则它很慢/不是 Pythonic。 Choosing between options 1 and 2 depends on what you're using it for;在选项 1 和选项 2 之间进行选择取决于您使用它的目的; different use cases call for different approaches (though indexing/iterating the bytes object would get you the int values if you need to use both forms).不同的用例需要不同的方法(尽管如果您需要使用两种形式,索引/迭代bytes对象会为您提供int值)。

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

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