cancel
Showing results for 
Search instead for 
Did you mean: 

How do I perform this function shorter ?

kemal
Associate II
Posted on April 17, 2015 at 12:43

unsigned long a;    

void assign(unsigned int a1,unsigned int a2)   

    {           

        if (a2==1)

    a =1;

         if (a2==2)

    a =2;

         if (a2==4)

    a =4;

         if (a2==8)

    a =8;

         if (a2==16)

    a =16;    

        if (a2==32)

    a =32;

         if (a2==64)

    a =64;

         if (a2==128)

    a =128;

         if (a2==256)

    a =256;

         if (a2==512)

    a =512;    

        if (a2==1024)

    a =1024;

         if (a2==2048)

    a =2048;

         if (a2==4096)

    a =4096;

         if (a2==8192)

    a =8192;

         if (a2==16384)

    a =16384;    

        if (a2==32768)

    a =32768;

    

        if (a1==1)

    a =65536;

         if (a1==2)

    a =131072;

         if (a1==4)

    a =262144;

         if (a1==8)

    a =524288;

         if (a1==16)

    a =1048576;    

        if (a1==32)

    a =2097152;

         if (a1==64)

    a =4194304;

         if (a1==128)

    a =8388608;

         if (a1==256)

    a =16777216;

         if (a1==512)

    a =33554432;    

        if (a1==1024)

    a =67108864;

         if (a1==2048)

    a =134217728;

         if (a1==4096)

    a =268435456;

         if (a1==8192)

    a =536870912;

         if (a1==16384)

    a =1073741824;    

        if (a1==32768)

    a =2147483648;

}

3 REPLIES 3
Posted on April 17, 2015 at 13:17

if (a2 <= 32768 && ((a2 == 1) || ((((a2 - 1) << 1) & a2) == a2))) a = a2;

if (a1 <= 32768 && ((a1 == 1) || ((((a1 - 1) << 1) & a1) == a1))) a = (long)a1 << 16;

JW
Posted on April 17, 2015 at 13:26

Use else to eliminate pointless comparisons or switch/case?

Understand the purpose, and desired function better?
Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
kemal
Associate II
Posted on April 17, 2015 at 14:20

This code

worked fine

if (a2 <= 32768 && ((a2 == 1) || ((((a2 - 1) << 1) & a2) == a2))) a = a2;
 if (a1 <= 32768 && ((a1 == 1) || ((((a1 - 1) << 1) & a1) == a1))) a = (long)a1 << 16;
 

1kb

was

my wife.

thanks

all