【发布时间】: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)>charBits(cl - '0');时,我得到了 00001000