T
T
thisall2021-09-11 17:49:32
C++ / C#
thisall, 2021-09-11 17:49:32

How to print the bit representation of a number?

#include <iostream>

using namespace std;

int main() {
    char value;

    cout << "Введите произвольное число от -128 до 127: ";
    cin >> value;

    cout << "Битовое представление числа " << value << " = " << bitset<sizeof(value) * CHAR_BIT>(value) << endl;
}


I wrote such a code and check with the number 12, 1100 should appear, and if it is 8 bit then 00001100, tell me why this code does not work?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2021-09-11
@thisall

The >> operator applied to cin mixes the cards for you. It assumes that if you enter one byte, it should be interpreted as one single character from the input stream.
The easiest way to change the program is something like this

#include <bitset>
#include <iostream>
#include <climits>

using namespace std;

int main() {
    int16_t temp;

    cout << "Введите произвольное число от -128 до 127: ";
    cin >> temp;
    
    char value=temp;

    cout << "Битовое представление числа " << value << " = " << bitset<sizeof(value) * CHAR_BIT>(value) << endl;
}

IDEONE

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question