Dariusz Majcherczyk
Dariusz Majcherczyk

Reputation: 59

Program to print all the bits of one byte union without using bitwise operators

I have to make a program which prints all the bits of one byte union (which can't be any bigger than that), without using bitwise operators. I got a problem to build suitable union which has only one byte because to my knowledge I can't use struct now, because struct has 4 bytes. This is what I've done already:





#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

Upvotes: 0

Views: 618

Answers (2)

Brecht Sanders
Brecht Sanders

Reputation: 7287

To print a byte in binary wit the most significant bit first you can do something like this:

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;
  }
}

Though in general I would advise to use bitwise operators as they translate better to machine code resulting in better performance. The same function looks something like this:

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;
  }
}

Note that your code prints the least significant bit first, which is not how binary is usually represented.

Upvotes: 1

Alex Lop.
Alex Lop.

Reputation: 6875

Maybe the point of this task is to use arithmetic operations instead of the bitwise ones? Here is an example:

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);
    }
}

See the output here: https://godbolt.org/z/xUC663

Upvotes: 2

Related Questions