Lets suppose i have n=4 so two 4-bit binary numbers. B1 = b1010
and B2 = b0110
.
I want to create an 8-bit number that looks like this b10100110
(B1B2).
How can i do such a thing in Java?
Multiply one by 16
, which is the same as adding four zeroes to the end. Then add them. In general, multiplying by 2^n
adds 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.