c - 如何在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;
}
这样对吗?我在我的算法中实现了这个嵌套循环,但它不能正常工作。
解决方案
可以使用 将整数的文本表示形式转换为其整数值strtoull()
。
char buf[sizeof(matrix)+1];
memcpy(buf, matrix, sizeof(matrix));
buf[sizeof(matrix)] = '\0';
result = strtoull(buf, NULL, 2);
推荐阅读
- ruby-on-rails - 如何使用 link_to 引用关联索引
- amazon-web-services - AWS 自动生成的电子邮件
- authentication - 如何跨微服务实现会话身份验证?
- graalvm - GraalVM/Polyglot:如何以编程方式获取 SourceLocation
- c# - 用 uint 计算
- tensorflow - tensorflow lite 示例对象检测中相机的屏幕尺寸
- javascript - 样式绑定 (Vue) 中的数据未更新
- flutter - 连续使用 FractionallySizedBox
- c# - ChromeWebDriver IJavaScriptExecutor 获取脚本值?
- javascript - 指定在 Zikula 中不起作用的 javascript 的加载顺序