```d
@safe:

void main()
{
    import std.stdio : writeln;
    writeln(ubyte(4).toHexDigit);
}

ubyte toHexDigit(ubyte decimal) pure nothrow @nogc
{
    if (decimal < 10)
        return (decimal + ubyte('0'));

    if (decimal < 16)
        return (decimal - ubyte(10) + ubyte('A'));

    return '\xFF';
}
```

```
onlineapp.d(12): Error: cannot implicitly convert expression `cast(int)decimal + 48` of type `int` to `ubyte` onlineapp.d(15): Error: cannot implicitly convert expression `cast(int)decimal - 10 + 65` of type `int` to `ubyte`
```

I guess, this fancy behavior is inherited from C.

I know this is advanced stuff, but the compiler *could* even prove that the calculation(s) won’t go beyond `ubyte.max`.

Reply via email to