连接两个数字的位的代码不起作用
任务是连接两个给定数字的二进制。
The task is to concat the binary of 2 given numbers.
示例:
给出 5
( 101
)和 3
( 011
),结果为 46
( concat(101,011)= 101011
)
Given 5
(101
) and 3
(011
), the result is 46
(concat(101, 011) = 101011
)
到目前为止的代码:
public class Concat {
public static void main(String[] args) {
int t = 0;
int k = 5;
int x = 3;
int i = 0;
while (i < 3) {
t = x % 2;
x /= 2;
k <<= 1;
k |= t;
++i;
}
System.out.println(k);
}
}
但是问题在于代码给出 101110
,而不是 101011
。
But the problem is that the above code gives 101110
, not 101011
.
什么是
您的问题是您正在向后 中输入第二个数字的位。这是因为 x%2
是低位:
Your problem is that you're feeding the bits of the second number in backwards. That's because x%2
is the low order bit:
+---+---+---+ <110
| 1 | 0 | 1 | <-----------------+^
+---+---+---+ |1
+---+---+---+ |1
| 0 | 1 | 1 | ----+0
+---+---+---+ 011>
Cringe 尽我最大的艺术才能:-)但是,如果您已经知道它是3位宽,只需使用:
Cringe at my awesome artistic abilities :-) However, if you already know that it's 3 bits wide, just use:
public class concat {
public static void main (String[] args) {
int t = 0;
int k = 5;
int x = 3;
k <<= 3;
k |= x;
// or, in one line: k = (k << 3) | x;
System.out.println(k);
}
}
就图形外观而言:
In terms of how that looks graphically:
+---+---+---+
k:| 1 | 0 | 1 |
+---+---+---+
+---+---+---+
x:| 0 | 1 | 1 |
+---+---+---+
+---+---+---+---+---+---+
k<<=3:| 1 | 0 | 1 | 0 | 0 | 0 |
+---+---+---+---+---+---+
+---+---+---+
x:| 0 | 1 | 1 |
+---+---+---+
+---+---+---+---+---+---+
k|=3:| 1 | 0 | 1 | 0 | 1 | 1 |
+---+---+---+---+---+---+
^ ^ ^
+---+---+---+
x:| 0 | 1 | 1 |
+---+---+---+
没有明显的理由一次这样做。
There's no apparent reason for doing it one bit at a time.