1

I am using the following function to extract n bits from a number. I got this function from here. For convenience I am posting it here. I would like to obtain bits from 0 to 9 and then in another statement bits 10 to 15. I am passing in 1033. I get the correct value of bits 0 to 9 but incorrect value for 10 to 15. I should get a 1 instead i am getting 1024 any suggestions ?

 unsigned createMask(unsigned a, unsigned b)
    {
        unsigned r = 0;
        for (unsigned i = a; i <= b; i++)
            r |= 1 << i;

        return r;
    }

Now i have this

unsigned short langId = 1033 ;// 10000001001
unsigned primary =   createMask(0,9) & langId; //gives 9 correct
unsigned sec = createMask(10,15) & langId;     //gives 1024 incorrect should be 1
MistyD
  • 16,373
  • 40
  • 138
  • 240

1 Answers1

1

The bits of sec that you've set are still in the 10-15 bit positions. You need to shift them back towards the start. Otherwise you have a single 1 set at position 10 and 210 is giving your answer of 1024

sec >> 10

Demo

Community
  • 1
  • 1
AndyG
  • 39,700
  • 8
  • 109
  • 143