Displaying input character’s binary value

  ascii, binary, c++

I’m trying to understand why I keep getting an unexpected binary result. For example, if I were to write
8
I will get a result of
00111000
and not
00001000

I’m not trying to manipulate to get another result, I’m trying to see what the actual data is for my input and understand why it’s giving that input.

I’m using C++ in visual studio with a platform of Win32.

This is my code:

#include <stdio.h>
#include <bitset>
#include <iostream>

using namespace std;
int main() {
    char cl;

    cout << "The minimum value of char is " << CHAR_MIN << endl;
    cout << "The maximum value of char is " << CHAR_MAX << endl;

    cout << "The storage size in byte(s) of a char is " << sizeof(cl) << endl;
    cout << "Input hexadecimal number in the data type of char for example a" << endl;

    scanf_s("%c", &cl, sizeof(cl));
    bitset < 8 * sizeof(cl)>charBits(cl);

    cout << "The converted binary value is " << charBits << endl;
    printf("The converted decimal value is% i n", cl);
}

Source: Windows Questions C++

LEAVE A COMMENT