How to convert a integer to a binary in C++20?

I am trying to convert a char into a binary. So first I used static_cast< int >(letter) then I used cout<<format("The binary value is {:b}",integer_value);.

I am using C++20 in Visual Studio 2019, so that is why I used format. However, I used it but it gives the wrong value. For example, I typed in k and it showed a binary value of 0b1101011, but this is wrong and on the internet I checked it and k should equal 01101011. My full code is shown.

#include <iostream>
#include <format>
using namespace std;

int main()
{
cout << "Enter a letter: " << endl;
char lett{};
cin >> lett;

switch (lett)
{
case 'A':
case 'a':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
cout << "You entered a vowel \n";
break;

default:
cout << "The letter is not a vowel \n";
break;

}



if (islower(lett))
{
    cout << "You entered a lower case letter \n";
}
else if (isupper(lett))
{
    cout << "The letter is not lower case \n";
}



// conver letter to lowercase and binary value 
int inti{(static_cast<int>(lett))};

cout << format("The lower case letter is {} and its binary value is 0b{:b} \n\n\n", static_cast<char>(tolower(lett)), inti);
return 0;
 }

Upvotes: 1

Views: 534

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51904

The output shown is numerically correct – it's just missing a leading zero. You can force the addition of leading zeros by specifying a field width (8) and add the 0 in the specifier.

The following line (using {:08b}) will output your binary value in the desired format:

cout << format("The lower case letter is {} and its binary value is 0b{:08b} \n\n\n", static_cast<char>(tolower(lett)), inti);

More details about format specifiers can be found on this cppreference page (specifically, the "fill and align" and "sign, #, and 0" sections, for this case).

Upvotes: 5

Related Questions