在 int 数组中打印出位
Print out bit in int array
我刚刚阅读了这个链接 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
相关文章:
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 链接列表运算符重载没有打印出我想要的内容
- 如何修改代码以打印出数组 v2
- 了解运算符重载和迭代器,为什么它会打印出"wrhrwwr"?
- 我用字符串做了一个C++构造函数,但它不会打印出字符串
- 以十六进制打印出 DWORD 会在 win32 c++ 中返回0x7FFFFFFF
- 使用递归反转和打印出数组的内容
- c++:如何打印出一个强制转换的 int 值?
- 如何在控制台上打印出带有数字 0-99 的简单数组
- 我们如何打印出C++ STL 容器的value_type?
- 打印出对象向量中的每个元素C++
- 我的字符串数组一次打印出前两个字符串
- 如何让我的重载<<运算符打印出我的函数?
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 二叉搜索树使用最常用的节点来打印出某些语句
- 使用模板打印出类
- 在 int 数组中打印出位
- 如何在不丢失第一位数字的情况下打印出双精度值
- c++位操作如何打印出16、32位
- C++ 打印出矢量<无符号字符的位集>