我需要计算表示为的位集之间的汉明距离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
s 更快,所以我写道:
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 *
to unsigned int *
safe?
2) 我在 32 位机器上工作,但我希望代码在 64 位机器上工作。做sizeof(unsigned int)
在两台机器上返回 4,还是在 64 位机器上返回 8?
3) If sizeof(unsigned int)
在 64 位机器中返回 4,我如何能够在 64 位类型上进行操作,long long
?
这是从unsigned char *
to unsigned int *
safe?
形式上,它给出了未定义的行为。实际上,它几乎可以在任何平台上运行if指针适当对齐unsigned int
。在某些平台上,如果对齐错误,它可能会失败或性能不佳。
Does sizeof(unsigned int)
在两台机器上返回 4,还是在 64 位机器上返回 8?
这取决于。有些平台有 64 位int
,有些是 32 位的。使用可能会有意义uint64_t
与平台无关;在 32 位平台上,您可以有效地展开循环(每次迭代处理两个 32 位值),这可能会带来一定的改进。
我怎样才能在 64 位类型上运行long long
?
uint64_t
,如果您有 C++11 或 C99 库。long long
至少为 64 位,但在 2011 年之前的实现中可能不存在。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)