打印数字的二进制表示 [英] printing the binary representation of a number

查看:107
本文介绍了打印数字的二进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码显示数字的二进制表示形式有什么问题?

What is wrong with the below code which prints the binary representation of a number?

int a = 65;
for (int i = 0; i < 8; i++) {
    cout << ((a >> i) & 1);
}

推荐答案

您是从数字的最低有效位开始并首先打印出来.但是,首先打印的内容是典型二进制表示形式中的最高有效位.

You're starting at the least significant bit in the number and printing it first. However, whatever you print first is the most significant digit in the typical binary representation.

65是01000001,这就是循环迭代的方式

65 is 01000001 so this is how your loop iterates

01000001
       ^   Output: 1

01000001
      ^    Output: 10

01000001
     ^     Output: 100

...

01000001
^          Output: 10000010

因此,打印输出是相反的.最简单的解决方法是更改​​循环顺序.

Thus the printed output is in reverse. The simplest fix is to change the order of the loop.

for (int i = 7; i >= 0; i--) {
   cout << ((a >> i) & 1);
}

这篇关于打印数字的二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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