Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set integer value as bit mask

Tags:

c

What is simplest way to assign a bit mask to integer value? For example I want integer with first, third and forth bits = 1, other = 0.

Certainly I am looking for code, not for single value! And certainly there lot of possibilities, but I try to find simplest and most descriptive looking

like image 984
Vladimir Avatar asked Nov 30 '22 10:11

Vladimir


1 Answers

I think the best way to think (!) is to just index bits from 0, and then apply "to set the n:th bit, bitwise-OR with the value (1 << n)":

int first_third_and_fourth = (1 << 0) | (1 << 2) | (1 << 3);
like image 182
unwind Avatar answered Dec 15 '22 04:12

unwind