How to set bits in bytes without a loop

I'm really confused, but can't complete a simple task, as it seems:

I just need to set the number of bits in a byte.

For instance:

I need to set 5 bits. Therefore I need 0xb00011111.

Is it possible to do this without a loop?

Also I would not like to write a lot #defines.

+4
source share
3 answers

For any integer n, fewer bits in a word, the required mask is:

const unsigned int mask = (1u << n) - 1;

No loop required.

Simple function:

unsigned int set_lsbs(unsigned int n)
{
  return (1u << n) - 1;
}

The top ten results:

0: 0x0
1: 0x1
2: 0x3
3: 0x7
4: 0xf
5: 0x1f
6: 0x3f
7: 0x7f
8: 0xff
9: 0x1ff

Note: the syntax is 0xb00011111not a binary literal, that 'b' is simply interpreted as a hexadecimal digit.

+9
source

5 :

mask = ~((~0u) << 5) ;

5 , 1, , 0.

, 8- :

uint8_t mask = ~((~0u) << 5) ;

, ( , 8 ):

  • ~0u ( ) = 0x11111111
  • 5 = 0x11100000
  • , = 0x00011111
+3

   ?

, set n , random , n .

   num = num | 1 << pos ;

5

num = num | 31 << pos;

31 ==> 1x2^0 + 1x2^1 + .. => 31 is the sum of 5 ones(1 1111)
0
source

Source: https://habr.com/ru/post/1689563/


All Articles