Let's say we have two int variables, A
and B
of bit length N < 16
and M < 16
respectively.
We want to have a new int variable C
such that the N
lowest bits contain the bits of A
and the next M
bits contain the bits of B
. (Assuming all variables are 32 bits long and little endian).
In my solution I slightly cheated by using binary strings instead:
int a = 65535;
int b = 65;
String cStr = Integer.toBinaryString(b) + Integer.toBinaryString(a);
int c = Integer.parseInt(cStr, 2);
But, how do I do it using bitwise operators?
Examples:
A=1, B=1 (N=1, M=1 resp.) then C = 11
A = 11000011010100, B = 101100 (N=14, M=6 resp.) then C = 10110011000011010100
In Java:
c = b << 16 | a;
But if you want to shift by the exact number of bits:
c = b << (32 - Integer.numberOfLeadingZeros(a)) | a;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With