【问题标题】:python version of C unsigned charC unsigned char的python版本
【发布时间】:2023-03-12 04:18:01
【问题描述】:

我需要有关此 C 代码的 python 版本的帮助:

#define HostBusy_high   0x02
#define control_register    0x37a

Out32 (control_register,(unsigned char)(Inp32(control_register) | HostBusy_high));

Out32 和 Inp32 是位于 inpout32.dll 中的函数,用于连接并行端口。这些函数将十六进制值作为其参数。我尝试在 python 中编写代码以获得所需的值,但这不是我得到的。请参阅下面的python版本:

from ctypes import windll

#parallel port instance
p_port = windll.inpout32
HostBusy_high = 0x02
control_register = 0x37a

write_data = write(p_port(Inp32(control_register) | HostBusy_high))
 Out32 (control_register,write_data))

使用上面的代码,我似乎没有得到我想要的值。我怀疑这是无符号值。

谢谢

【问题讨论】:

  • 需要更多上下文。你想用字节值做什么?
  • user680730,无意冒犯,但考虑到您的历史@stackoverflow,我建议您先阅读 Python 教程,并且仅在仍有不清楚的地方提问。给你:docs.python.org/tutorial/index.html

标签: python char


【解决方案1】:

取决于你为什么需要一个无符号字符。大多数情况下,您将只使用 Python 整数。如果您实际上需要一个一字节的数据,您可以使用 Python 的 struct.pack 从一个整数中生成一个一字节的字节字符串。

如果不充分了解源语言和目标语言以及要翻译的代码主体,通常无法通过逐行字面翻译语言之间的代码来获得良好的结果。

【讨论】:

    【解决方案2】:

    也许你应该得到你的价值的模 256。那么它肯定是未签名的。例子:

    >>> 12 % 256
    12
    >>> 1022 % 256
    254
    >>> -1 % 256
    255
    >>> -127 % 256
    129
    

    【讨论】:

    • 在这种情况下,也许他应该只为一个变量分配一个 0..255 范围内的值? :)
    • 我不确定他想要什么。也许他得到 -128 和 127 之间的值,并且当它是负数时需要二进制补码。不过不确定。
    【解决方案3】:

    您可以在 ctypes 库中找到具有 c_ubyte 数据类型的匹配项。看看你是否用你的值填充了该类型的对象,并找出它是否合适。

    https://docs.python.org/3/library/ctypes.html#ctypes.c_ubyte

    其余类型列表在 https://docs.python.org/3/library/ctypes.html#fundamental-data-types

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 2013-07-21
      相关资源
      最近更新 更多