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


No comments: