C中的Shift运算符

use*_*290 -2 c

我有一个长度为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功能我想要移位运算符(<<)来提高效率.我怎样才能做到这一点?

Eri*_*hil 5

#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.