Loop 0x0000 to 0xFFFF

I need a loop that uses UInt16 (ushort) to loop through all its values. However, this does not happen:

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

The problem is that the loop will stop when I == 0xFFFF and not "do something." If I changed the for statement to for (ushort i = 0; i <= UInt16.MaxValue; i ++), then it becomes an infinite loop because I never get to 0x10000 because ushorts only goes to 0xFFFF.

I could make an "i" int and drop it or assign ushort variable to it in a loop.

Any suggestions?

+6
c # loops for-loop
source share
5 answers

Use a do...while

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

There is an interesting discussion of test cycles above and below here .

+17
source share

UInt16.MaxValue is evaluated to 0xffff , not 0x10000 . I think you can do this with a do / while , as a burkhard1979 answer option.

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

You can simply replace for with a do-while loop.

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

Does it need to be short? why not just

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

Assuming your code suffers from shutdown with a single error (the current code stops before the final evaluation). Then the following may answer you.

Very simple, since your counter is a 16-bit unsigned integer, it cannot have a value greater than 0xffff , since this value is still valid, you need to have some value that goes beyond the scope of this parameter as a defender. However, adding 1 to 0xffff in 16 bits just wraps around to 0 . As suggested, use a do while loop (which does not require a protective value) or use a larger value to contain your counter.

ps. Using 16-bit variables on modern machines is actually less efficient than using 32-bit variables, since there is no need to generate overflow code.

+1
source share

All Articles