反转位数 [英] Reverse bits in number
本文介绍了反转位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有二进制数1011,它等于十进制11.我想要反转位的位置使它变为1101,即十进制13.这里是代码:
For example, I have the binary number 1011 which is equal to decimal 11. I want the reverse bit's location such that it become 1101, which is decimal 13. Here is code:
import java.util.*;
public class bits {
public static void main(String[] args) {
Scanner scnr=new Scanner(System.in);
System.out.println("enter x:");
int x=scnr.nextInt();
int b=0;
while (x!=0){
b|=( x &1);
x>>=1;
b<<=1;
}
System.out.println(b);
}
}
但是当我输入x 11时它会输出26。这是什么错误?
But when I enter x 11 then it prints 26. What is the mistake?
推荐答案
你正在转移 b
一次许多。首先进行转换(这是第一次,当 b == 0
时,它没有效果):
You are shifting b
one time too many. Do the shift first (so that the first time, when b == 0
, it has no effect):
while (x!=0){
b<<=1;
b|=( x &1);
x>>=1;
}
这篇关于反转位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文