Friday, October 21, 2011

Register, Mask and Value


#include <stdio.h>


char *basecalc(unsigned int num, unsigned int base)
{
    static char buff[32];
    char *s = &buff[31];
    int cnt = 0,i;
    *s = '\0';
    while(num)
    {
        *(--s) = "0123456789ABCDEF"[num%base];
        num /= base;
        cnt++;
        if(cnt>7) break;
    }
    for(i=cnt;i<=7;i++)
        *(--s) = '0';
    return s;
   
}

int fbs(int mask)
{
    unsigned int pos = 0;
    if(!mask) return 0;
    while(!(mask &1))
    {
        mask >>= 1;
        pos++;
    }
    return (pos);
}

int setmask (int num, int mask, int value)
{
    /*This multiplies value by the lowest set bit in MASK.
      The multiplier is known to be a constant power of 2 at compile time,
      so this will be compiled as a simple left shift by any remotely sane compiler.
     */
    //value *= ( mask & ~(mask << 1));
    //return (num &= (value | ~mask) );
    return ( num &= ((value*(mask & ~(mask<<1)))|~mask )  );
}

int main()
{
    int num, mask, value,res;

    printf("Enter the num: ");
    scanf("%d",&num);      
    printf("Enter the mask: ");
    scanf("%d",&mask);
    printf("Enter the value: ");
    scanf("%d",&value);

    /* ------------------------ */
    printf("Num  : %s\n",basecalc(num,2));
    printf("Mask : %s\n",basecalc(mask,2));
    printf("Value: %s\n",basecalc(value,2));
    /* ------------------------ */

    res = setmask(num,mask,value);
    printf("The set value: %s\n",basecalc(res,2));
    return 0;
}

TEST 1
Enter the num  : 25
Enter the mask : 24
Enter the value: 1
Num            : 00011001
Mask           : 00011000
Value          : 00000001
The set value  : 00001001

TEST 2
Enter the num  : 153
Enter the mask : 24
Enter the value: 2
Num            : 10011001
Mask           : 00011000
Value          : 00000010
The set value  : 10010001

No comments: