ubyte + ubyte = int

Salih Dincer salihdb at hotmail.com
Thu Oct 27 01:57:15 UTC 2022


On Wednesday, 26 October 2022 at 21:10:54 UTC, 0xEAB wrote:
> I know this is advanced stuff, but the compiler *could* even 
> prove that the calculation(s) won’t go beyond `ubyte.max`.
> ```d
> //... => char?
>         return (decimal - ubyte(10) + ubyte('A'));
> 
>     return '\xFF';
> }
> ```

You should help the compiler with return type:

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

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

     return '\xFF';
}
void main()
{
   import std.stdio : writeln;
   foreach(ubyte n; 0..256)
   {
     const c = n.toHexDigit();
     if(n < 16)
     {
       c.writeln(": ", n);
     } else assert(c == char.init);
   }
} /*
0: 0
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
A: 10
B: 11
C: 12
D: 13
E: 14
F: 15

Process finished.
*/
```
SDB at 79




More information about the Digitalmars-d-learn mailing list