我需要做一个程序,在不使用位运算符的情况下,打印一个字节联合体(不能再大了)的所有位。我遇到了一个问题,如何建立一个只有一个字节的联合体,因为据我所知,我现在不能使用struct,因为struct有4个字节。这是我已经做的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"
int main(void) {
printf("Input number: ");
if (scanf("%hhu", &word.x) == 0) {
printf("Incorrect input");
return 1;
}
printf("%u %u %u %u %u %u %u %u", word.a+0, word.a+1, word.a+2, word.a+3, word.a+4, word.a+5, word.a+6, word.a+7);
return 0;
}
#ifndef bit_set
#define bit_set
typedef unsigned char byte;
byte x;
union bit {
unsigned int i : 1;
}foo;
union bit_set
{
union bit a[8];
byte x;
}word;
#endif
也许这个任务的重点是使用算术运算而不是位运算,这里有一个例子。
void printByteBits(unsigned char num)
{
const static int div[8] = {1, 2, 4, 8, 16, 32, 64, 128};
for (int i = 0; i < sizeof(div)/sizeof(div[0]); i++)
{
printf("Bit %d: %d\n", i, (num / div[i]) % 2);
}
}
看这里的输出: https:/godbolt.orgzxUC663
要打印一个二进制的字节,先打印最重要的位,你可以这样做。
void print_bits (unsigned char x)
{
int i;
for (i = 0; i < 8; i++) {
if (x >= 0x80)
printf("1");
else
printf("0");
x = x / 2;
}
}
不过一般来说,我建议使用位运算符 因为它们能更好地转化为机器代码,从而提高性能. 同样的函数看起来像这样。
void print_bits (unsigned char x)
{
int i;
for (i = 0; i < 8; i++) {
if (x & 0x80 != 0)
printf("1");
else
printf("0");
x = x << 1;
}
}
请注意你的代码是先打印最不重要的位, 而二进制通常不是这样表示的.