【问题标题】:Displaying input character's binary value显示输入字符的二进制值
【发布时间】:2021-06-13 08:20:06
【问题描述】:

我试图了解为什么我不断得到意外的二进制结果。例如,如果我要写 8 我会得到一个结果 00111000 并不是 00001000

我不是试图操纵以获得另一个结果,而是试图查看我的输入的实际数据是什么,并了解它为什么提供该输入。

我在 Visual Studio 中使用 C++,平台为 Win32。

这是我的代码:

#include <stdio.h>
#include <bitset>
#include <iostream>

using namespace std;
int main() {
    char cl;

    cout << "The minimum value of char is " << CHAR_MIN << endl;
    cout << "The maximum value of char is " << CHAR_MAX << endl;

    cout << "The storage size in byte(s) of a char is " << sizeof(cl) << endl;
    cout << "Input hexadecimal number in the data type of char for example a" << endl;

    scanf_s("%c", &cl, sizeof(cl));
    bitset < 8 * sizeof(cl)>charBits(cl);

    cout << "The converted binary value is " << charBits << endl;
    printf("The converted decimal value is% i \n", cl);
}

【问题讨论】:

  • 没看懂,为什么你加了iostream以及stdio的头文件?
  • 我不确定这与 [assembly]、[cpu-registers] 和 [microprocessors] 标签有什么关系,您似乎只是想将一个字符打印为二进制.. . 另外,为什么使用scanf_s 而不是cin 甚至getchar?为什么printf 在所有这些couts 之后?
  • 另外,当你写 8 时,它会得到包含字符 8 的 ASCII 值,我相信它是 56。所以你的程序很好,你只需要查找 ASCII 表。
  • 是的,我刚刚检查了00111000 的十进制值,它是56。在这里,我建议你以后看看ASCII 表。 asciitable.com如果要获取实际数字,请将scanf_s中的格式字符串由"%c"改为"%hhd"
  • 哇,是的,你对 ASCII 的看法是对的,它解释了很多。哦,是的,当我写 sizeof(cl)&gt;charBits(cl - '0'); 时,我得到了 00001000

标签: c++ binary ascii


【解决方案1】:

输入的值是一个 ASCII 字符,您应该在打印之前将该值转换为相应的数字。在 ASCII 中,字母 'a'-'f' 的范围是 97-102,'A'-'F' 的范围是 65-70,'0'-'9' 的范围是 48-57。所以在得到你的输入后,用if's 测试它的 ASCII 值并相应地减去:

// Subtracting 87 converts 'a' to 10 and 'f' to 15, the numerical representations
// of those hexadecimal values, which are then converted to binary by bitset.
if (cl >= 97 && cl <= 102)
    cl -= 87;
// Subtract 10 less again for the same reason above.
else if (cl >= 65 && cl <= 70)
    cl -= 55;
// Subtracting 48 from '0' converts it to the number 0 in memory,
// and subtracting 48 from '9' converts it to the number 9.
else if (cl >= 48 && cl <= 57)
    cl -= 48;

您会注意到这会破坏十进制打印,因此您应该将数字转换为十进制以便像 cout &lt;&lt; static_cast&lt;int&gt;(cl) &lt;&lt; endl; 这样打印。

【讨论】:

  • 一个简单的static_cast&lt;int&gt;(cl) 可能比使用to_string 更好。另外,我建议您将散布在代码中的幻数替换为字符文字,以使其更易于理解。 另外,我认为没有理由在 A/aF/f 的情况下减去,除非你想找到它在字母表中的位置(在这种情况下,你能说出你为什么选择减去 10?就像减去 87 而不是 97?)。
  • 从 'a' 中减去 10 会将其转换为内存中的 10,即 'a' 的十六进制表示。我添加了 cmets 来展示这一点。另外,是的,演员可能是更好的选择,所以我改变了。
  • 啊,好吧,我没有这么想过。很公平,你赢得了我的支持;)。我仍然建议您将幻数替换为字符文字,但由于您已经事先记录了 ASCII 值,因此这不是绝对必要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 2020-05-15
相关资源
最近更新 更多