Home > Software design >  Reproducing functionality of a C function
Reproducing functionality of a C function

Time:10-24

I have to reproduce the functionality of this test function and I dont´really know where to start. I can only use specific oprators and 12 operations at max.

int test_dl10(int parameter1, int parameter2)
{
    int result = 0;
    int i;
    for (i = parameter2; i <= parameter1; i  )
        result |= 1 << i;
    return result;
}

CodePudding user response:

The functions set all bits from parameter2 to parameter1.

See code below mixed with example for p2=2, p1=4. The result should be 0b11100 in binary where bit 2,3, and 4 are set.

Parameter names were shortened to p1 and p2 for brevity.

// use unsigned to avoid issues with overflows
unsigned result;
// set all bits from 0 to p1
result = 1u << (p1   1);      // becomes 1 << (4   1) = bin 00100000
result--;              // bin 00100000 - 1 = bin 00011111
// clear lower p2 bits
result = result >> p2; // bin 00011111 >> 2 = 00000111
result = result << p2; // bin 00000111 << 2 = 00011100

Done in 5 operations. Code works as long as 0 <= p2, p1 < bits of int - 1.


Edit

Testing it for a full range of bits for 32-bit integer where no UB is invoked (i.e. 1 << 31 typically overflows int)

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

int test_dl10(int parameter1, int parameter2)
{
    int result = 0;
    int i;
     for (i = parameter2; i <= parameter1; i  )
         result |= 1 << i;
     return result;
}

int test_dl101(int p1, int p2)
{
    
    // use unsigned to avoid issues with overflows
unsigned result;
// set all bits from 0 to p1-1
result = 1u << (p1   1);      // becomes 1 << 5 = bin 00100000
result--;              // bin 00100000 - 1 = bin 00011111
// clear lower p2 bits
result = result >> p2; // bin 00011111 >> 2 = 00000111
result = result << p2; // bin 00000111 << 2 = 00011100

    return  result;
}

int main(void)
{
    for (int p1 = 0; p1 <= 30;   p1)
    for (int p2 = 0; p2 <= 30;   p2)
    if (test_dl10(p1,p2) != test_dl101(p1,p2)) {
       printf("%d %d\n", p1,p2);
       return -1;
    }
    puts("Passed");
}

prints Passed

CodePudding user response:

int test_dl101(int parameter1, int parameter2)
{
    return   (((1ULL << ((parameter1 >= parameter2) * (parameter1 - parameter2   1))) - 1) << parameter2) ;

}

Assuming paramter1 & parameter2 in range <0 : sizeof(int)*CHAR_BIT-1>

  • Related