[英]Compare 64-bit integers by segments
我有兩個 64 位整數x
和y
。 每個代表5個無符號短整數:前10位代表第一個整數,接下來的13位代表第二個整數,接下來的16位代表第三個整數,接下來的14位代表第四個整數,其余位代表第 5 個整數。
設x0
, x1
, x2
, x3
, x4
是構成x
的 5 個短整數。 設y0
, y1
, y2
, y3
, y4
是構成y
的 5 個短整數。 我需要知道是否x0 < y0
AND x1 < y1
AND x2 < y2
AND x3 < y3
AND x4 < 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
未全面測試!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.