使用8位无符号整数变量作为计数器循环遍历256个值 [英] Loop over 256 values using 8-bit unsigned integer variable as counter

查看:182
本文介绍了使用8位无符号整数变量作为计数器循环遍历256个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我只是想用连续数字0-255填充缓冲区.我对此没多想,最终陷入了无限循环.

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;
}

问题在于,i永远不会是256,因为它在255之后会翻转为零.

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

我的问题是,有没有办法在不将i增大到16位值的情况下执行此循环?

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

注意:我知道我可以将循环更改为i<255并为最终位置添加另一行,但是我试图找出一种更好的方法.

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.

推荐答案

uint8_t txbuf[256];
uint8_t i = 0;

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

uint8_t txbuf[256];
uint8_t i = 255; 

do {
   txbuf[i] = i;  
} while (i--);

这篇关于使用8位无符号整数变量作为计数器循环遍历256个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆