gpt4 book ai didi

c++ - 我们如何使用强制转换来允许将字符屏蔽为字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:21 26 4
gpt4 key购买 nike

我需要尽可能快地执行此操作数百万次。假设我有两个包含几个短 char 数组的列表:

"a b ", "a c ", "a x ", etc...
" w z", " w y", " q b"

现在我想从每个列表中形成一个组合。例如,"a b ""w z" 将变为 "awbz"

似乎最有效的方法是将它们存储为 32 位序列:

"a b " --> 0x00620061
" w z" --> 0x7A007700

现在 OR 他们在一起得到

0x7A627761 --> "awbz"

我的第一个想法是使用 union ,但我知道这在技术上会出现未定义的行为......写入 union 变量的一部分,然后从 union 中读取不同类型。

union {
unsigned char[4] c;
unsigned int i;
};

我的第二个想法是使用强制转换在 int 和 char[] 之间切换。有没有办法安全地这样做?

最佳答案

在 C++ 中,始终允许对 char* 进行类型双关。所以你很幸运。

只需使用 int32_t 来存储您建议的值。将按位或的结果存储在一个变量中,并在其地址上使用 reinterpret_cast

int32_t first = 0x00620061;
int32_t second = 0x7A007700;
int32_t combined = first | second;
std::string s(reinterpret_cast<const char*>(&combined), 4);

演示:http://ideone.com/1KGBl

关于c++ - 我们如何使用强制转换来允许将字符屏蔽为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9040456/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com