Home > Back-end >  Merge binary Strings and Insert bits in C
Merge binary Strings and Insert bits in C

Time:02-20

Function insertBits

X and Y are two integer values.

The function insertBits must insert all the bits of Y after the last set bit in X. Then the function must return an integer representing the revised value of X.

Input:

10 14

Output:

188

Explanation:

10 -> 1010
14 -> 1110

After inserting 1110 after the last set bit in 1010 the binary representation of X becomes 10111100.
The decimal equivalent of 10111100 is 188.


Input:

152 9

Output:

2504

Explanation:

152 -> 10011000
9 -> 1001

After inserting 1001 after the last set bit in 10011000, the binary representation of X becomes 100111001000.
The decimal equivalent of 100111001000 is 2504.

This is my code:

#include <stdio.h>
#include <stdlib.h>

long bin(long n)
{
    long d,r,binary=0;
    d=n;
    int temp=1;
    while(n!=0)
    {
        r=n%2;
        n=n/2;
        binary=binary r*temp;
        temp=temp*10;
    }
    return binary;
}


int insertBits(int X, int Y)
{
    bin(X);
    bin(Y);

     ///
    
}

int main()

{

    int X, Y;
    scanf("%d %d", &X, &Y); 
    printf("%d", insertBits(X, Y)); 
    return 0;

}

I converted decimal into binary. But I don't know how to insert the bits in X.

CodePudding user response:

Don't use decimal arithmetic. Binary is simpler and clearer:

uint32_t bitshift(uint32_t x, uint32_t y)
{
    // put y in the result
    uint32_t result = y;
    // shift by the trailing 0s in x
    while (x && !(x & 1)) {
        x /= 2;
        result *= 2;
    }
    // find the shift for x, which is larger than result
    uint32_t shift = 1;
    while (shift && shift <= result) shift *= 2;
    // put x in the right place
    result |= x * shift;
    return result;
}

int main()
{
    printf("10 14 = %5u\n",bitshift(10,14));
    printf("152 9 = %5u\n",bitshift(152,9));
    // Test some corner cases
    printf("152 0 = %5u\n",bitshift(152,0));
    printf("0 152 = %5u\n",bitshift(0,152));
    printf("4 4   = %5u\n",bitshift(4,4));
    printf("1 0xffffffff = %5u\n",bitshift(1,0xffffffffU));

}

Output:

10 14 =   188
152 9 =  2504
152 0 =    19
0 152 =   152
4 4   =    48
1 0xffffffff = 4294967295

CodePudding user response:

You should use unsigned int arguments, compute the number of trailing zeroes in X and the number of bits in Y and the result will be easy to obtain with shift operations:

unsigned int insertBits(unsigned int X, unsigned int Y) {
    int n1, n2;
    unsigned int temp;
    if (X == 0)
        return Y;
    if (Y == 0)
        return X;
    // compute the number of trailing zeroes in X
    for (n1 = 0, temp = X; (temp & 1) == 0; n1  , temp >>= 1)
         continue;
    // compute the number of bits in Y
    for (n2 = 0, temp = Y; temp != 0; n2  , temp >>= 1)
         continue;
    return ((X >> n1 << n2) | Y) << n1;
}
  • Related