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.