python - 将实现特定的 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++ 程序的行为被编译开。
解决方案
根据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
笔记:
我认为初始化
std::string s = "αa";
有点关键。所以,这取决于源代码编码。(我在 Windows 上。像许多 Windows 应用程序一样使用 Windows-1252 编码会破坏这个程序,因为字符串只有两个元素。我刚刚意识到Window-1252甚至不编码α
,但这并没有不要让它变得更好。)强制字符为, 应该使应用程序独立于C++ 编译器
unsigned char
特定类型的签名。char
推荐阅读
- asp.net-mvc - DataFormatString = "{0:N}" 不适用于模型 MVC
- java - 如何在不使用 jsoup 的情况下从 webview 获取 html 代码?
- python - 如何在 tkinter Text 小部件中动态插入文本?
- ruby-on-rails - mingw32:轨道上的钥匙
- css - 将侧边栏放在正下方,而不设置任何 `top` 或 `bottom` 值
- javascript - 创建新的 React 应用程序时“找不到名称 'div'.ts(2304)”?
- asp.net - 在域 ASP.NET 上的另一台服务器上使用 Windows 身份验证 Active Directory 自动登录
- python-3.x - Discord.py 按名称查找成员并将成员移动到语音频道
- typescript - 推断回调参数的类型
- typescript - Typescript - 从 npm 包接口部分覆盖类型