[英]How can i create from two n-bit binary numbers a 2n-binary number?
Lets suppose i have n=4 so two 4-bit binary numbers.假设我有 n=4 所以两个 4 位二进制数。
B1 = b1010
and B2 = b0110
. B1 = b1010
和B2 = b0110
。
I want to create an 8-bit number that looks like this b10100110
(B1B2).我想创建一个类似于
b10100110
(B1B2) 的 8 位数字。
How can i do such a thing in Java?我怎么能用Java做这样的事情?
Multiply one by 16
, which is the same as adding four zeroes to the end.将 1 乘以
16
,这与在末尾添加四个零相同。 Then add them.然后添加它们。 In general, multiplying by
2^n
adds n zeroes
.通常,乘以
2^n
会添加n zeroes
。
You can of course multiply and add them as suggested.您当然可以按照建议将它们相乘和相加。 I prefer using bit manipulation operators.
我更喜欢使用位操作运算符。
int b1 = 0b1010;
int b2 = 0b0110;
// shift b1 left 4 bits and then OR it with b2.
int result = (b1<<4)|b2;
System.out.println(Integer.toBinaryString(result));
As a side note, for every bit you shift left, you are multiplying by a power of 2. So shifting left by 4 bits is multiplying by 16. For right shifting, you are dividing by powers of 2.作为旁注,对于您左移的每一位,您都乘以 2 的幂。因此,左移 4 位就是乘以 16。对于右移,您正在除以 2 的幂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.