首页 > 解决方案 > 如何在c中逐位连接?

问题描述

我有尺寸为 8x8 的“1”和“0”矩阵。我需要将整个矩阵逐位存储在一个unsigned long long变量中。我怎样才能做到这一点?

例如,让我们以 2x2 的 '1' 和 '0' 的矩阵为例: 矩阵 2x2:

1 0
0 1

变量必须包含: 1001 位。相同的示例,但在矩阵 8x8 和 unsigned long long 变量上。

这就是我试图做的:

#include <stdio.h>

int main()
{
  unsigned long long result = 0;
  char matrix[8][8]; // lets that the matrix is already filled by '1' and '0'
  for (i=0; i<SIZE; i++)
   {
     for (j=0; j<SIZE; j++)
      {
        result = result | ((unsigned long long)(matrix[i][j] - '0'));
        result <<= 1;
      }
   }
   return 0;
}

这样对吗?我在我的算法中实现了这个嵌套循环,但它不能正常工作。

标签: cstringmatrixbit-manipulationbits

解决方案


可以使用 将整数的文本表示形式转换为其整数值strtoull()

char buf[sizeof(matrix)+1];
memcpy(buf, matrix, sizeof(matrix));
buf[sizeof(matrix)] = '\0';
result = strtoull(buf, NULL, 2);

推荐阅读