Set/Unset Bits Operation

  • Thread starter Thread starter O.B.
  • Start date Start date
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);
 
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);
}
 
O.B. said:
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 was just thinking when reading the first post that you should shift
the mask and the value instead of shifting the original. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top