在 int 数组中打印出位



我刚刚阅读了这个链接 http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/1-C-intro/bit-array.html我有一个问题,我正在制作一个 128 位数组,所以我使用数组 int A[4]。我可以设置位和测试位,但如何打印出这些位,例如000001000.....?我用一个简单的代码来打印它

for(int i=0;i<128;i++)
{
cout<<A[i];// i tried cout << static_cast<unsigned int>(A[i]);
}

结果不是我想要的在此处输入图像描述

感谢您的阅读。

测试位并根据结果打印 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 位
  • 您有一个 4x int 变量的数组,而不是 128x 个"一位"变量

更喜欢这样的东西:

#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

最新更新