Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over 256 values using 8-bit unsigned integer variable as counter

Tags:

c

loops

So I was just trying to fill a buffer with consecutive numbers 0-255. I didn't think much on it and ended up in an infinite loop.

uint8_t i;
uint8_t txbuf[256];

for (i=0; i<256; i++) {
    txbuf[i] = i;
}

the problem being that i will never be 256 as it rolls over to zero after 255.

my question is, is there a way to do this loop without bumping i up to a 16 bit value?

Note: I know I could change the loop to i<255 and add another line for the final spot but I'm trying to figure out of there is a nicer looking way.

like image 962
user3817250 Avatar asked Dec 05 '14 17:12

user3817250


People also ask

How to define unsigned int in c++?

Unsigned int data type in C++ is used to store 32-bit integers. The keyword unsigned is a data type specifier, which only represents non-negative integers i.e. positive numbers and zero.

Why we use unsigned int in C?

Unsigned int is a data type that can store the data values from zero to positive numbers whereas signed int can store negative values also. It is usually more preferable than signed int as unsigned int is larger than signed int.

Should I use unsigned int c++?

Unsigned integers ( size_t , uint32_t , and friends) can be hazardous, as signed-to-unsigned integer conversions can happen without so much as a compiler warning.

Why we write unsigned int before a variable?

This is implemented for fetching values from the address of a variable having an unsigned decimal integer stored in memory. An unsigned Integer means the variable can hold only a positive value. This format specifier is used within the printf() function for printing the unsigned integer variables.


1 Answers

uint8_t txbuf[256];
uint8_t i = 0;

do {
   txbuf[i] = i;  
} while (i++ != 255);

or

uint8_t txbuf[256];
uint8_t i = 255; 

do {
   txbuf[i] = i;  
} while (i--);
like image 198
zavg Avatar answered Nov 15 '22 22:11

zavg