1

Suppose we have a continuous process where we increment an unsigned char +1 or -1 and we want it to always stay in a range between 0 , 2^n - 1,lets say for example that this range is 0 , 15, I know that it is possible to do something like this:

unsigned char offset = 0;

while( condition )
{
    if(something)
    {
       offset += 1;
    }else
    {
       offset -= 1;
    }
    offset %= 16;
}

I wanted to know if it is possible to the same thing with bit fields, and whether it had any benefits:

unsigned char offset : 4;
offset = 0;

while( condition )
{
    if(something)
    {
       offset += 1;
    }else
    {
       offset -= 1;
    }
}

I am asking because if I understand it correctly, the first version will perform the % at every loop iteration, while the second will only do it ( if what I read is correct) when offset tries to overflow.

9
  • Arithmetic over- and under-flow of unsigned integers is well-defined. When you over- or under-flow an unsigned integer it will roll over. For example if you have unsigned short v; then v = 65535; ++v; will make v zero. And v = 0; --v will turn v into 65535. Commented Oct 14, 2020 at 8:34
  • Right. There is no unsigned overflow, when you reach the max for the unsigned type, it will be reduced modulo back to 0. Commented Oct 14, 2020 at 8:34
  • @DavidC.Rankin yeah I understand that, my question was whether it is correct to assume that the second version is safe and faster due to less % calls? Commented Oct 14, 2020 at 8:37
  • 2
    That I can't give you a yes/no on without going back to the standard and reading the bitfield section again on structs -- there are a few limitation that apply directly to bitfields -- and I have this nagging feeling that a bitfield cannot be treated as a type for this purpose. It's type is unsigned char so if you are expecting the 4-bits carved out by it to behave as a full type -- I don't think it does for this purpose. Commented Oct 14, 2020 at 8:55
  • 1
    C11 Standard - 6.2.6 Representations of types(p4) specifically excludes the word "type" when describing the m:bits that make up a bit-field. So jury is still out on that one... Commented Oct 14, 2020 at 9:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.