Showing posts with label Bit Manipulations. Show all posts
Showing posts with label Bit Manipulations. Show all posts

Friday, October 21, 2011

Create Mask


/* Create a mask with m set bits followed by n unset bits */

#include <stdio.h>


unsigned int createmask(unsigned int m, unsigned int n)
{
    return (~(~0 << m) << n);
}

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

int main()
{
    unsigned int m,n,r;
    printf("Enter the required set bits: ");
    scanf("%d",&m);
    printf("Enter the required unset bits: ");
    scanf("%d",&n);
    r = createmask(m,n);
    printf("The created mask: %s\n",basecalc(r,2));
    return 0;
}

Test 1:
Enter the required set bits  : 5
Enter the required unset bits: 3
The created mask             : 11111000

Test 2:
Enter the required set bits  : 2
Enter the required unset bits: 5
The created mask             : 01100000


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