Bitwise operations in C: setting bits on the left

Given an integer like 10, how can I write 10 1 bits (starting from the left) for a total of 16 bits, for example:

11111111.11000000 

Or, if an integer of 4 is given, it will write:

 11110000.00000000 

Thank you, I'm still learning C and not familiar with bitwise operations.

+4
source share
3 answers

-(1 << wordsize - numbits) should do this.

It is instructive to see what happens in your example. 1 << wordsize - numbits is 1 << 12 , which is 00010000.00000000 . Remembering that -x = ~x+1 , we calculate ~(1 << 12) = 11101111.111111 . Add 1 and you will get 11110000.00000000 .

+3
source

In fact, an int is usually 32 bits. But I just put 16 bits in the comment to make it more understandable.

 int i = 0; //00000000 00000000 int mask = 65536; //10000000 00000000 int retVal = 0; //00000000 00000000 int yourAmountOfBitsToOne = 2; for(i = 0; i < yourAmountOfBitsToOne; i++){ retVal = retVal | (mask >> i); } printf("%d", retVal); 

If you run this, the output should be 216 + 215 = 98304.

Why?

Iteration 0:

 line 1: retVal = 00000000 00000000 | (10000000 00000000 >> 0) line 1: retVal = 10000000 00000000 

Iteration 1:

 line 1: retVal = 10000000 00000000 | (10000000 00000000 >> 0) line 1: retVal = 10000000 00000000 | (01000000 00000000) line 1: retVal = 11000000 00000000 

After completion is complete, you print an integer value of 11000000 00000000 , which is 98304 .

Create a function that prints int retVal differently, this will make it easier to verify that the output is correct. And this is also a very good exercise for learning bitwise operators.

Hope this helps.

+1
source

ints are usually 32 bits. If you mean short integers, then:

 unsigned short MakeMask16(unsigned short width,unsigned short offsetFromLeft) { unsigned short mask = -1; mask <<= (sizeof(unsigned short)*8-width); mask >>= offsetFromLeft; return mask; } 

Or all in one line:

 unsigned short MakeMask16(unsigned short width,unsigned short offsetFromLeft) { return (unsigned short(-1<<(sizeof(unsigned short)*8-width)) >> offsetFromLeft); } 

Please note that if you did not drop it to the unsigned sign in front of the right offset, then the 1 that you thought you were moving on the left side will still be there. If you do not need to shift to the left, you can ignore this and discard the right shift.

0
source

All Articles