Darius Ionut
Darius Ionut

Reputation: 49

bit mask left shift

I tried to solve a problem but I don't know if it's the good solution.

Build a mask of type unsigned long with the 14 least significant bits (from the right) set to 1;

#include <stdio.h>
#include <stdlib.h>
unsigned long mask;
int main()
{
    int i;
    for(i=0;i<14;i++)
        mask|=(1<<i);
    printf("%li",mask);
    return 0;
}

Upvotes: 3

Views: 2110

Answers (1)

Solaine Charron
Solaine Charron

Reputation: 131

It is better

#include <stdio.h>
#include <stdlib.h>
unsigned long mask;
int main()
{
    int num = 14;
    mask = (1 << num) - 1;
    printf("%lu", mask);
    return 0;
}

Here num is total number of least significant bits.

How it Works

Binary representation of 2^14 = 16348 is 0000000000000000 0100000000000000‬(In 32 bit) and

binary representation of 2^14-1 = 16347 is 0000000000000000 0011111111111111‬

So 14 least significant bits set to 1.

Upvotes: 9

Related Questions