如何在 C++20 中将整数转换为二进制?

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

我正在尝试将 char 转换为二进制。所以首先我使用 static_cast< int >(letter) 然后我使用 cout<<format("The binary value is {:b}",integer_value);.

我在 Visual Studio 2019 年使用 C++20,所以这就是我使用格式的原因。但是,我使用了它,但它给出了错误的值。例如,我输入 k,它显示二进制值 0b1101011,但这是错误的,我在互联网上查了一下,k 应该等于 01101011。显示了我的完整代码。

#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;
 }

显示的输出在数字上是正确的——只是少了一个前导零。您可以通过指定字段宽度 (8) 并在说明符中添加 0 来强制添加前导零。

以下行(使用 {:08b})将以所需格式输出二进制值:

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

有关格式说明符的更多详细信息,请参见 this cppreference page(具体来说,“填充和对齐”和“符号、# 和0" 部分,对于这种情况)。