I've written a small operation that sets/unsets bits within an
unsigned integer. Is there a better way to do this?
static uint setBits(uint original, uint newValue, uint offset, unint
mask)
{
return ((original >> offset) & (~mask) | newValue) << offset;
}
Example:
uint test = 0xEC; // 1110 1100
uint TwoBitMask = 0x03;
uint offset = 3;
// Expect 1110 0100
uint result = setBits(test, 0, offset, TwoBitMask);
// Expect 1111 1100
result = setBits(test, 3, offset, TwoBitMask);
// Expect 1111 0100
result = setBits(test, 2, offset, TwoBitMask);
O.B. - 06 Jul 2007 17:23 GMT
Small bug in that last one (bits dropped when shifted). Let's try
that again:
static uint setBits(uint original, uint newValue, uint offset, uint
mask)
{
return original & ~(mask << offset) | (newValue << offset);
}
> I've written a small operation that sets/unsets bits within an
> unsigned integer. Is there a better way to do this?
[quoted text clipped - 21 lines]
> // Expect 1111 0100
> result = setBits(test, 2, offset, TwoBitMask);
Göran Andersson - 06 Jul 2007 20:17 GMT
> Small bug in that last one (bits dropped when shifted). Let's try
> that again:
[quoted text clipped - 4 lines]
> return original & ~(mask << offset) | (newValue << offset);
> }
I was just thinking when reading the first post that you should shift
the mask and the value instead of shifting the original. :)

Signature
Göran Andersson
_____
http://www.guffa.com