[英]How to count number of bits set for a 128-bit integer
我想在C中使用128位無符號整數。我編寫了以下代碼:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include <stdint.h>
#include <limits.h>
#define unt __uint128_t
#define G1 226854911280625642308916404954512140970
int countSetBits(unt n){
int count = 0;
while(n){ n &= (n-1) ; count++; }
return count;
}
int main(){
printf(" %d\n",countSetBits(G1) );
}
雖然輸出應該是64,G1的位數,它是96.我使用gcc編譯器。 我知道GMP GNU,但出於我的目的,我需要快速執行。 因此我想避免使用GNU庫。
由於此處說明的問題,您需要使用兩個64位值分配常量:
#include <stdio.h>
#define uint128_t __uint128_t
#define G1 ((uint128_t)12297829382473034410 << 64 | (uint128_t)12297829382473034410)
int countSetBits(uint128_t n) {
int count = 0;
while(n) {
n &= (n - 1);
count++;
}
return count;
}
int main() {
printf(" %d\n",countSetBits(G1) );
}
輸出:
64
onlinegdb中提供實時版本。
C語言中沒有128個常量,因此您需要使用兩個64位值並將它們組合在一起
#define unt __uint128_t
#define G1 ((((__uint128_t)0xaaaaaaaaaaaaaaaaull) << 64) + ((__uint128_t)0xaaaaaaaaaaaaaaaaull))
int countSetBits(unt n){
int count = 0;
while(n){ n &= (n-1) ; count++; }
return count;
}
int countSetBits1(unt n){
int count = 0;
while(n)
{
count += n & 1;
n >>= 1;
}
return count;
}
int main(){
printf(" %d\n",countSetBits(G1) );
printf(" %d\n",countSetBits1(G1) );
}
由於你使用的是一個gcc擴展,我認為更多是可以的。 gcc具有一系列內部函數,用於返回常規整數類型中的設置位數。 根據您的CPU和gcc選項,這將成為適當的指令,或者回退到調用庫函數。
就像是:
int bitcount_u128(unsigned __int128 n) {
uint64_t parts[2];
memcpy(parts, &n, sizeof n);
return __builtin_popcountll(parts[0]) + __builtin_popcountll(parts[1]);
}
如果將x86處理器與popcnt
指令popcnt
使用(在過去十年中最常用),請使用-mpopcnt
或相應的-march=
設置進行編譯以使用硬件指令。
或者,如果您可以使用popcnt
限制對x86處理器的支持,則可以使用<nmmintrin.h>
的_mm_popcnt_u64()
內在函數來代替__builtin_popcountll()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.