On Fri, 25 Feb 2011 13:52:53 -0500, Andrej Mitrovic <[email protected]> wrote:

So I'd like to print all values storable in a byte in hex representation:

import std.stdio;
void main()
{
    int counter;
    foreach (byte index; byte.min..byte.max)
    {
        if (!(counter % 4))
            writeln();
       writef("%#.2x, ", index);
        counter++;
    }
}

If you run this, you'll realize that it doesn't print the final 0x7F. This is because in a foreach range literal (is that the correct term?), the left side is inclusive, but the right side isn't.

Hence this will run the foreach from 0 to 9:
foreach (index; 0..10) { }

So I figured I'd just add a +1 at the end, but then I get an error:
    foreach (byte index; byte.min..byte.max+1)
    {
    }

Error: cannot implicitly convert expression (128) of type int to
byte.

Of course 128 can't fit in a byte. But how am I supposed to print out the last value if the right hand side of a range literal is non-inclusive?

foreach(int index; byte.min..byte.max + 1)

The truth is, you don't want to use byte to represent your comparisons, because byte.max + 1 isn't a valid byte.

And instead of counter, you can use a formula instead:

if((index - byte.min) % 4 == 0)
   writeln();

-Steve

Reply via email to