如何读取二进制数作为输入? [英] How to read a binary number as input?

查看:89
本文介绍了如何读取二进制数作为输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户是否可以使用C或C ++输入二进制数?

Is there a way for the user to input a binary number in C or C++?

如果我们编写类似

int a = 0b1010;
std::cout << a << std::endl

然后输出为10(使用适当的编译器扩展时)。

Then the output comes out to be 10 (when using the appropriate compiler extensions).

,但是当我们尝试写

int n;
std::cin >> n;
int t = 0bn;

这给我们带来了一个错误,所以有人可以建议我们如何直接将二进制数读取为输入而不是使用字符串存储输入?

It gives us an error so can anyone suggest that how can we directly read binary number as input rather than using string to store input?

推荐答案

这里有些混乱,让我们对其进行一些整理。

There is a bit of confusion here, let's disentangle it a bit.


  • 0b1010 整数文字,是一个常量,可编译以2为底的时间整数值。同样, 0xA 是以16为底的文字,而 10 以10为底。 。所有这些都指向相同的整数,这只是告诉编译器您要表示哪个数字的另一种方式。在运行时,在内存中,该整数始终以2为底的数字表示。

  • 0b1010 is an integer literal, a constant, compile-time integer value written in base 2. Likewise, 0xA is a literal in base 16 and 10 is in base 10. All of these refer to the same integer, it is just a different way of telling the compiler which number you mean. At runtime, in memory, this integer is always represented as a base-2 number.

std :: cout<<一个;接受 a 的整数值,并输出其字符串表示形式。默认情况下,它以10为底进行输出,但您可以使用 std :: hex 修饰符,使其在基数16中输出。没有预定义的修饰符以二进制格式打印。因此,您需要自己执行此操作(或使用Google进行搜索,这是一个常见问题)。

std::cout << a; takes the integer value of a and outputs a string representation of it. By default it outputs it in base 10, but you can i.e use the std::hex modifier to have it output it in base 16. There is no predefined modifier to print in binary. So you need to do that on your own (or google it, it is a common question).

0b 仅用于定义整数文字。它不是不是运行时操作符。回想一下,所有 int 都以内存中的基数2表示。从机器角度来看,其他基数不存在, int int ,因此没有任何要转换的内容。如果您需要从字符串中读取二进制数,则可以将反向代码滚动到要打印的内容上( std :: cin>> n 假定输入是一个以10为底的数字,因此,如果输入实际上打算以2为底,那么它将读取一个错误的数字。

0b at last, is only used to define integer literals. It is not a runtime operator. Recall, all ints are represented as base 2 numbers in memory. Other bases do not exist from a machine point of view, int is int, so there is nothing to convert. If you need to read a binary number from a string, you would roll the reverse code to what you do to print it (std::cin >> n assumes that the input is a base 10 number, so it reads a wrong number if the input is actually intended to be in base 2).

这篇关于如何读取二进制数作为输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆