O
O.B.
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);
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);
