Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear code for counting from 0 to 255 using 8-bit datatype

I was wondering if there is a clean way of counting from 0 to 255 using an 8 bit datatype, something like:

for(uint8_t i(0);i<=255;++i)
{
    ....
}

This obviously will not work but it makes it clear you want to count from 0 to 255.

A working solution would be something like:

uint8_t i(0);
do
{
    ...
    ++i;
}
while(i > 0);

But here it is not at all clear it counts from 0 to 255.

This will also work but it is just ugly IMHO:

uint8_t i(0);
while(true)
{
    ...
    if (i == 255)
    {
        break;
    }
    ++i;
}

So I was wondering, is there a clean way of doing this without using a larger datatype?

EDIT:

  • I like the version using for because it makes its intend clear without thinking: looping from 0 to 255. All other versions require some thought about what is going on and therefore more likely to confuse others.
  • I do not want to use int because the code is for a 8-bit microcontroller with not much memory.
like image 723
rve Avatar asked Nov 10 '09 13:11

rve


5 Answers

What about:

uint8_t i = 0;
do {
    ...
} while (i++ != 255);
like image 145
ot. Avatar answered Nov 18 '22 09:11

ot.


I'm not sure what you mean but

 uint8_t i = 0;

 do {
    ...
 } while (++i & 255) ;

should do what you ask and has an explicit reference to 255 (useless if your compiler is C99 standard and uint8_t is really 8 bits).

like image 25
Remo.D Avatar answered Nov 18 '22 09:11

Remo.D


What's wrong with the obvious?

i = 255;
do {
 work();
} while (i--);
like image 37
Dipstick Avatar answered Nov 18 '22 08:11

Dipstick


You seem to want to convey the message of counting from 0 to 255 by the data type you are using, but what's the significance of 255? You should probably #define this magic number with a name explicitly stating the purpose of it. Also, a comment above the statement would be way more helpful than trying to "encode" all that information in somewhat weird looking statements.

For example:

#define MAX_RETRIES   255
unsigned int retries;

for(retries = 0; retries <= MAX_RETRIES; ++retries)
{
  do_retry_work();
}

If needed, add a comment, why the number of retries is limited to 255.

like image 39
cschol Avatar answered Nov 18 '22 07:11

cschol


I would suggest that the simple solution:

for (int i = 0; i < 256; ++i) {
   ...
}

is probably also going to be the most efficient solution.

  1. Even if you use a smaller (1-byte) data type. The C compiler will promote it to an int in any expression.

  2. On an 8-bit controller an int is probably 16-bits. Using a single-byte type will only save one byte of stack space. Then again the compiler may put that variable in a register, so there will not be any space savings anyway.

Check the assembly code generated by the above code, then decide whether or not it needs (space) optimization.

like image 29
Ferruccio Avatar answered Nov 18 '22 08:11

Ferruccio