【问题标题】:How to convert a integer to a binary in C++20?如何在 C++20 中将整数转换为二进制?
【发布时间】:2021-09-20 14:59:33
【问题描述】:

我正在尝试将 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;
 }

【问题讨论】:

  • 011010111101011 是同一个数字。如果你想要前导零,你可以使用像0b{:08b}这样的格式传递一个宽度。
  • 有几件事可能会出错,例如输入,转换为不同的整数类型,或最后格式化和输出。缩小范围以找出其中哪些失败了。

标签: c++ visual-studio binary c++20


【解决方案1】:

显示的输出在数字上是正确的——它只是缺少一个前导零。您可以通过指定字段宽度 (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”部分,用于本例)。

【讨论】:

    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2011-04-29
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多