Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate binary representation of two ints

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

like image 341
Jill White Avatar asked Sep 07 '18 12:09

Jill White


1 Answers

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;
like image 182
rghome Avatar answered Sep 28 '22 16:09

rghome