我需要计算表示为 char
数组的位集之间的汉明距离。这是一个核心操作,所以它必须尽可能快。我有这样的东西:
const int N = 32; // 32 always
// returns the number of bits that are ones in a char
int countOnes_uchar8(unsigned char v);
// pa and pb point to arrays of N items
int hamming(const unsigned char *pa, const unsigned char *pb)
{
int ret = 0;
for(int i = 0; i < N; ++i, ++pa, ++pb)
{
ret += countOnes_uchar8(*pa ^ *pb);
}
return ret;
}
分析后,我注意到对 int
的操作速度更快,所以我写道:
const int N = 32; // 32 always
// returns the number of bits that are ones in a int of 32 bits
int countOnes_int32(unsigned int v);
// pa and pb point to arrays of N items
int hamming(const unsigned char *pa, const unsigned char *pb)
{
const unsigned int *qa = reinterpret_cast<const unsigned int*>(pa);
const unsigned int *qb = reinterpret_cast<const unsigned int*>(pb);
int ret = 0;
for(int i = 0; i < N / sizeof(unsigned int); ++i, ++qa, ++qb)
{
ret += countOnes_int32(*qa ^ *qb);
}
return ret;
}
问题
1) 从 unsigned char *
到 unsigned int *
的转换安全吗?
2) 我在 32 位机器上工作,但我希望代码在 64 位机器上工作。 sizeof(unsigned int)
在两台机器上都返回 4,还是在 64 位机器上返回 8?
3) 如果 sizeof(unsigned int)
在 64 位机器上返回 4,我将如何使用 long long
对 64 位类型进行操作>?
最佳答案
Is that cast from
unsigned char *
tounsigned int *
safe?
形式上,它给出了未定义的行为。实际上,如果指针适合 unsigned int
对齐,它几乎可以在任何平台上工作。在某些平台上,如果对齐错误,它可能会失败或性能不佳。
Does
sizeof(unsigned int)
returns 4 in both machines, or is it 8 on a 64-bit one?
这取决于。有些平台有 64 位 int
,有些平台有 32 位。无论平台如何,使用 uint64_t
可能是有意义的;在 32 位平台上,您将有效地展开循环(每次迭代处理两个 32 位值),这可能会带来适度的改进。
how would I be able to operate on a 64-bit type, with
long long
?
uint64_t
,如果您有 C++11 或 C99 库。 long long
至少为 64 位,但在 2011 年之前的实现中可能不存在。
关于c++ - 按位运算。此代码安全且可移植吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18658615/