在int数组中打印出位
问题描述:
我刚刚阅读这个链接http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/1-C-intro/bit-array.html 我有一个问题,我做了一个128位数组,因此我使用了一个数组int A [4]。我可以设置位和测试位,但如何将这些位打印出来,例如000001000 .....? 我用一个简单的代码来打印在int数组中打印出位
for(int i=0;i<128;i++)
{
cout<<A[i];// i tried cout << static_cast<unsigned int>(A[i]);
}
结果是不是我要找的 enter image description here
感谢您的阅读。
答
根据结果测试位并打印0或1。
for(int i=0;i<128;i++) {
if((A[i/32]>>(i%32))&1) {
cout<<'1';
} else {
cout<<'0';
}
}
,或者更简单的:
for(unsigned i=0; i<128; ++i) {
cout << ((A[i/32]>>(i%32))&1);
}
(这一切都假定A是某种类型的,它至少32位宽的阵列;理想地,这将是uint32_t
)
答
您正在一对夫妇不幸的假设:
- 的
int
并不总是32位 - 你有4个
int
变量,而不是128倍“一位”的数组变量
喜欢的东西是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h> /* uint32_t comes from here */
void main(void) {
int i, j;
uint32_t t;
uint32_t data[4];
/* populate the data */
for (i = 0; i < 4; i++) {
data[i] = rand();
}
/* print out the 'bits' for each of the four 32-bit values */
for (i = 0; i < 4; i++) {
t = data[i];
/* print out the 'bits' for _this_ 32-bit value */
for (j = 0; j < (sizeof(data[0]) * 8); j++) {
if (t & 0x80000000) {
printf("1");
} else {
printf("0");
}
t <<= 1;
}
printf("\n");
}
}
输出:
01101011100010110100010101100111
00110010011110110010001111000110
01100100001111001001100001101001
01100110001100110100100001110011
别t垃圾邮件标签。这不是C.并且不要发布文字的图像。提供[mcve]。 – Olaf
如果您声明了4个int元素的数组,则引用索引0 ... 3之外的任何元素将调用* undefined behavior *,这是您的代码在该循环过程中执行124次的一些操作。 – WhozCraig
@WhozCraig谢谢,那么你能指导我解决它的一些方法吗? – Van