Jill White
Jill White

Reputation: 63

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

Upvotes: 6

Views: 3907

Answers (2)

rghome
rghome

Reputation: 8841

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;

Upvotes: 7

Ilya Grigoryan
Ilya Grigoryan

Reputation: 259

try this and check if you have the same value. I am not sure how it will be in java, but this work for C++ and C# int c = b << 16 | a;

first you should calculate how much to shift b. so:

int a = 65535;
int count = 0;
int temp = a;
while(temp != 0)
{
  ++count;
  temp = temp >> 1;
}

int b = 65;
int c = b << count | a;

Upvotes: -1

Related Questions