按段比较 64 位整数



我有两个 64 位整数xy。它们中的每一个都表示 5 个短无符号整数:前 10 位表示第一个整数,接下来的 13 位表示第 2 个整数,接下来的 16 位表示第 3 个整数,接下来的 14 位表示第 4 个整数,其余位表示第 5 个整数。

x0x1x2x3x4构成x的5个短整数。设y0y1y2y3y4构成y的5个短整数。我需要知道x0 < y0x1 < y1x2 < y2x3 < y3x4 < y4.

我认为最简单的解决方案是转移:

bool allLess(std::size_t x, std::size_t y)
{
if(x >= y) return 0;
int shift[] = {10, 13, 16, 14};
for(int i = 0; i < 4; ++i)
{
x <<= shift[i];
y <<= shift[i];
if(x >= y) return 0;
}
return 1;
}

我知道有很多按位体操。有什么更快的解决方案吗?

这并没有真正回答提出的问题,但解决了一个非常相似的问题: (如果能够重新组织实际问题,例如OP,这可能会有所帮助(

如果整数不是紧密打包的(即,如果每个"字段"之间和MSB端有一个零位填充(,并且您想知道<=而不是<,我认为您可以只减去数字并检查是否有任何填充位更改。(即。(y - x) & PADDING_MASK(

您可以使用位字段

#include <iostream>
#include <string.h>
#include <stdint.h>
struct CombInt64 {
CombInt64(uint64_t x) {
memcpy(this, &x, sizeof(uint64_t));
}
bool operator < (const CombInt64& other) const {
std::cout << "Debug: self.a: " << a << " other.a: " << other.a << std::endl;
std::cout << "Debug: self.b: " << b << " other.b: " << other.b << std::endl;
std::cout << "Debug: self.c: " << c << " other.c: " << other.c << std::endl;
std::cout << "Debug: self.d: " << d << " other.d: " << other.d << std::endl;
std::cout << "Debug: self.e: " << e << " other.e: " << other.e << std::endl;
return a < other.a && b < other.b && c < other.c && d < other.d && e < other.e;
}
#if __BYTE_ORDER == __LITTLE_ENDIAN
uint64_t a:10;
uint64_t b:13;
uint64_t c:16;
uint64_t d:14;
uint64_t e:11;
#elif __BYTE_ORDER == __BIG_ENDIAN
uint64_t e:11;
uint64_t d:14;
uint64_t c:16;
uint64_t b:13;
uint64_t a:10;
#endif
};
bool allLess(uint64_t x, uint64_t y) {
return CombInt64(x) < CombInt64(y);
}
int main(void) {
std::cout << allLess(123, 45) << std::endl;
}

输出

[root@localhost tmp]# ./a.out
Debug: self.a: 123 other.a: 45
Debug: self.b: 0 other.b: 0
Debug: self.c: 0 other.c: 0
Debug: self.d: 0 other.d: 0
Debug: self.e: 0 other.e: 0
0

未经过全面测试!!

最新更新