首页 > 解决方案 > 将实现特定的 C++ char 与 Python 中的 uint32_t 匹配

问题描述

考虑以下 C++ 程序:

#include <cstdint>
#include <iostream>

int main() {
  std::string s = "αa";
  std::cout << std::hex << uint32_t(s[0]) << std::endl;
  std::cout << std::hex << uint32_t(s[1]) << std::endl;
  std::cout << std::hex << uint32_t(s[2]) << std::endl;
}

哪个打印

ffffffce
ffffffb1
61

如何在 Python 中复制强制转换行为?IE。如何获得包含 3 个数字的 uint32_t 类型的 numpy 数组?1

例如

import numpy as np

s = "αa"
s = s.encode('utf-8')
for c in bytearray(s):
    h = print(hex(np.uint32(c)))

将导致

0xce
0xb1
0x61

这是不够的。我还研究了ctypes模块提供的功能,但找不到可行的解决方案。

动机:我想应用一个Fowler–Noll–Vo 哈希函数,它依赖于按位操作,匹配现有的 C++ 实现,该实现通过将 a 的元素转换为std::string来操作uint32_t

1虽然 C++ 版本的输出取决于体系结构/编译器,但我正在寻找一个与此问题中描述的行为相匹配的实现,或者在使用与 python 解释器相同的编译器进行编译时 C++ 程序的行为被编译开。

标签: pythonc++numpycastingctypes

解决方案


根据Python 文档。

bytearray 类型是 0 <= x < 256 范围内的可变整数序列。

恕我直言,C++ 中的转换因此应将字符处理为unsigned char. 这可以通过“两步”演员来实现:

#include <cstdint>
#include <iostream>

typedef unsigned char uchar;

int main() {
  std::string s = "αa";
  std::cout << std::hex << uint32_t((uchar)s[0]) << std::endl;
  std::cout << std::hex << uint32_t((uchar)s[1]) << std::endl;
  std::cout << std::hex << uint32_t((uchar)s[2]) << std::endl;
}

输出:

ce
b1
61

Live Demo on coliru

笔记:

  1. 我认为初始化std::string s = "αa";有点关键。所以,这取决于源代码编码。(我在 Windows 上。像许多 Windows 应用程序一样使用 Windows-1252 编码会破坏这个程序,因为字符串只有两个元素。我刚刚意识到Window-1252甚至不编码α,但这并没有不要让它变得更好。)

  2. 强制字符为, 应该使应用程序独立于C++ 编译器unsigned char特定类型的签名。char


推荐阅读