Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set bits in byte without loop

I am really confused, but cannot to do simple task as it seems:

I simply need to set number of bits in byte.

For example:

I need 5 bits set. So I need 0xb00011111.

Is it possible to do this without loop?

Also I'd not like to write lot of #defines too.

like image 229
Bulkin Avatar asked Dec 14 '22 19:12

Bulkin


1 Answers

For any integer n less than the number of bits in the word, the mask you need is:

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

No loop required.

A simple function using this:

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

The ten first results are:

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

Note: the syntax 0xb00011111 is not not a binary literal, that 'b' is simply interpreted as a hex digit.

like image 51
unwind Avatar answered Dec 28 '22 20:12

unwind