简体   繁体   English

从0x0000循环到0xFFFF

[英]Loop from 0x0000 to 0xFFFF

I'd like a loop that uses a UInt16 (ushort) to loop through all of its values. 我想要一个使用UInt16(ushort)循环遍历其所有值的循环。 However, this doesn't do it: 但是,这不会这样做:

for( ushort i = 0; i < UInt16.MaxValue; i++ )
{
    // do something
}

The problem is that the loop will quit when i == 0xFFFF and not "do something". 问题是,当i == 0xFFFF而不是“做某事”时,循环将退出。 If I change the 'for' statement to "for(ushort i = 0; i <= UInt16.MaxValue; i++ )", then it becomes an infinite loop because i never gets to 0x10000 because ushorts only go to 0xFFFF. 如果我将'for'语句更改为“for(ushort i = 0; i <= UInt16.MaxValue; i ++)”,那么它将变为无限循环,因为我永远不会达到0x10000因为ushorts只转到0xFFFF。

I could make 'i' an int and cast it or assign it to a ushort variable in the loop. 我可以使'i'成为一个int并将其转换为或者将它分配给循环中的ushort变量。

Any suggestions? 有什么建议么?

Use a do...while loop 使用do...while循环

ushort i = 0;
do
{
    // do something
} while(i++ < UInt16.MaxValue);

There is an interesting discussion of testing loops at the top vs. the bottom here . 有一个在顶部或底部测试循环的一个有趣的讨论在这里

UInt16.MaxValue evaluates to 0xffff , not 0x10000 . UInt16.MaxValue计算结果为0xffff ,而不是0x10000 I think you can do this with a do / while loop, as a variation on burkhard1979's answer. 我认为你可以用do / while循环来做这个,作为burkhard1979答案的一个变种。

ushort i = 0;
do {
   ...
} while (++i != 0);

You could simply replace the for by a do-while loop. 您可以简单地用do-while循环替换for。

ushort i = 0;
do
{
i++;
...
} while(i!=UInt16.MaxValue);

does it have to be a short? 它必须是短吗? why not just 为什么不呢

for(int i = 0;i<=0xFFFF;i++)
{
  //do whatever
}

Assuming that your code suffers from an off by one error (the current code, stops just before having the final value evaluated. Then the following might answer you. 假设您的代码遭遇一个错误(当前代码,在评估最终值之前停止。那么以下可能会回答您。

Very simple, as your counter is a 16 bit unsigned integer, it can not have values bigger than 0xffff , as that value is still valid, you need to have some value that extends beyond that as the guard. 很简单,因为你的计数器是一个16位无符号整数,它的值不能大于0xffff ,因为该值仍然有效,你需要有一些超出保护的值。 However adding 1 to 0xffff in 16 bits just wraps around to 0 . 但是,在16位中添加10xffff只会回绕到0 As suggested, either use a do while loop (that does not need a guard value), or use a larger value to contain your counter. 如建议的那样,要么使用do while循环(不需要保护值),要么使用更大的值来包含计数器。

ps. PS。 Using 16 bit variables on modern machines is actually less efficient than using 32 bit variables as no overflow code needs to be generated. 在现代机器上使用16位变量实际上比使用32位变量效率低,因为不需要生成溢出代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM