Apothem

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.

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.