我有一个长度为64的二进制数组.我想在C中找到相应的整数.我编写了以下代码.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
main()
{
int A[64]={1, 1, 1, 1, 1,1, 1, 1, 1, 1,1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1,1,1,1},i;
long long int B=0;
for(i=0;i<64;i++)
B=B+A[i]*pow(2,63-i);
printf("B=%llu\n",B);
}
Run Code Online (Sandbox Code Playgroud)
结果还可以.但是代替pow功能我想要移位运算符(<<)来提高效率.我怎样才能做到这一点?
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
int main(void)
{
int A[64] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
uint64_t B = 0;
for (int i = 0; i < 64; ++i)
B |= (uint64_t) A[i] << 63-i;
printf("B = %" PRIu64 ".\n", B);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
笔记:
B
更改为未签名的类型,特别是uint64_t
为了避免溢出.uint64_t
使用而不是unsigned long long
意义的清晰度和精确度.printf
与类型匹配B
.