Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit mask in C

Tags:

What is the best way to construct a bit mask in C with m set bits preceded by k unset bits, and followed by n unset bits:

00..0 11..1 00..0   k     m     n 

For example, k=1, m=4, n=3 would result in the bit mask:

01111000 
like image 803
grigy Avatar asked Nov 25 '08 06:11

grigy


People also ask

What is a bit mask in C?

Bit masking is simply the process of storing data truly as bits, as opposed to storing it as chars/ints/floats. It is incredibly useful for storing certain types of data compactly and efficiently.

What is bit masking with example?

To represent a set of N items we need a sequence of N bits where every bit represents an item in the Set. This sequence of bits used to represent a subset of a set is usually referred to as a mask. For example, the sequence of bits 10101 is a mask used to represent a set of size 5.

What is a bit mask value?

In Bitmasking, the idea is to visualize a number in the form of its binary representation. Some bits are “set” and some are “unset” , “set” means its value is 1 and “unset” means its value is 0. A “Bitmask” is simply a binary number that represents something.


2 Answers

~(~0 << m) << n

like image 54
Darius Bacon Avatar answered Nov 17 '22 11:11

Darius Bacon


So, you are asking for m set bits prefixed by k reset bits and followed by n reset bits? We can ignore k since it will largely be constrained by the choice of integer type.

mask = ((1 << m) - 1) << n; 
like image 26
Jonathan Leffler Avatar answered Nov 17 '22 12:11

Jonathan Leffler