View Full Version : C/C++: Bit setting procedure?

11-16-2011, 05:07 AM
How would you go about setting a bit in an integer variable WITHOUT the introduction of variables/loops/branches/etc.

i.e. let's have something like:

// num = num to set; any 32 bit int
// bit = 1 or 0
// pos = 0 <= pos <= 31
// Assume Little Endian & ints are 32 bits and that right bit shift is logical (not arithmetic).
int bit_set(int num, int bit, int pos) {
// some code here
return num;

What can be done to set the num's bit at pos to bit, such that no extra variable, any branches (which encases loops), or structs/objects are introduced? In other words, bit setting with just plain operators. I can't really figure this out; I can think of how to do it by introducing one extra variable or branches, but not of a way without them.

11-16-2011, 03:24 PM
I may be missing something about the requirement, but wouldn't you just do:

num |= bit<<pos;


11-18-2011, 11:02 AM
The problem is that what if the bit at that pos is 1 but you want to set it to 0? The or operator would make no difference.

I think I found the solution looking around a bit more:
1. Set the bit to 0
2. Set the bit to <bit>

num = num & ~(1<<pos);
num = num | (bit << pos);

11-18-2011, 03:02 PM
Ah yes, you're right!

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum