0

For example; when I write 3, i am getting 00110011

6 -> 00110110

69 -> 00110110

I used int8_t, uint8_t, uint_least8_t etc. And I got same error. What is the reason of starting with 0011? I am using Visual Studio and Windows10.

#include <bitset>
#include <cstdint>
#include <iostream>

int main()
{
    std::uint_fast8_t numb;
    std::cout << "Please type an unsigned integer (0-255): ";
    std::cin >> numb;
    std::bitset<8> bits = static_cast<std::bitset<8>>(numb);
    std::cout << bits << '\n';
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 3
    As if the `3` or the `6` or the first 6 of the `69` was being interpreted as a `char` in ASCII. – Eljay Jun 17 '21 at 15:24
  • 2
    is `numb == 3` or `numb == '3'`? – Jarod42 Jun 17 '21 at 15:25
  • If I have such issue the very first thing I would do I would initialize `numb` with 3, comment out `std::cin` and see if the same problem persists. Novadays people do not bother to think, they immediately post to SO. – Slava Jun 17 '21 at 15:31
  • I suppose ultimately the answer is "C compatibility" but it's frustrating that C++ doesn't just allow explicit conversions between `char`s and integral representations thereof, but mandates implicit conversions. – Nathan Pierson Jun 17 '21 at 15:33
  • @NathanPierson mandates implicit conversions of what sorry? – Slava Jun 17 '21 at 15:38
  • @Slava The fact that `uint8_t` almost certainly actually _is_ `unsigned char`, rather than convertible to and from `unsigned char`, because `unsigned char` is an unsigned integer type. So you get things like `uint8_t x = 3; std::cout << x;` not printing `3`. – Nathan Pierson Jun 17 '21 at 15:54
  • @NathanPierson `char` or `unsigned char` are integral types. `std::istream` and `std::ostream` just treat them as symbol stored there that's it. So there is no implicit conversions, but there are no special types for characters in C++. You can create a class to store a symbol and prohibit implicit conversion to/from integral types, just creators of the language do not see need for that. – Slava Jun 17 '21 at 16:44

0 Answers0