gpt4 book ai didi

c - 如何计算为 128 位整数设置的位数

转载 作者:行者123 更新时间:2023-12-01 22:05:14 38 4
gpt4 key购买 nike

我想在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 库。

最佳答案

由于解释了一个问题 here ,您需要使用两个 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 位整数设置的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52348103/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com