0

I have implemented in C++ print_in_binary_format() function, which (as the name states) print 8-bit number in binary:

void print_in_binary_format(std::uint8_t number)
{
    for (int bit_index = 7; bit_index >= 0; --bit_index) {
        std::cout << ((number & (1U << bit_index)) ? '1' : '0');
    }
    std::cout << '\n';
}

But it doesn't work as supposed, i.e.:

  • Input: 2

  • Output: 00110010

  • Input: 0

  • Output: 00110000

I know that in C++ I could use bitset library, but it is not the case. I would like to know what is wrong with this function, my brain is stuck!

There is whole program to test that:

#include <cstdint>
#include <iostream>



std::uint8_t read_user_number();
void print_in_binary_format(std::uint8_t number);



int main()
{
    std::uint8_t number {};
    number = read_user_number();
    print_in_binary_format(number);

    return EXIT_SUCCESS;
}



std::uint8_t read_user_number()
{
    std::cout << "Enter a number (0-255): ";
    std::uint8_t user_number {};
    std::cin >> user_number;

    return user_number;
}



void print_in_binary_format(std::uint8_t number)
{
    for (int bit_index = 7; bit_index >= 0; --bit_index) {
        std::cout << ((number & (1U << bit_index)) ? '1' : '0');
    }
    std::cout << '\n';
}

1 Answers1

1

The problem is your input data. You are providing 2 or 0 as a character, not as a number.

Let me explain:

  • character '2' -> ASCII 0x32, 32 is the real input of your function, 00110010 is the bit representation of 0x32.
  • character '0' -> ASCII 0x30 has 00110000 as binary representation.

Hence the function above is working.

In order to solve the issue look at the way you are collecting the input data.

My 2 cents, Ste.

Stefano Buora
  • 1,052
  • 6
  • 12