天天看點

d整提升示例1

​​原文​​

@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';
}      

會報錯.

錯誤:無法​​

​int​

​​類型的​

​cast(int)decimal-10+65​

​​表達式​

​隐式轉換​

​​為​

​ubyte​

​​.

但是編譯器可​​

​證明​

​​計算不會超出​

​ubyte.max​

​​.

​​​參考​​ 你可以這樣:

return ((decimal & 0xf) + ubyte('0'));
return ((decimal & 0xf) - ubyte(10) + ubyte('A'));      
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

完成
*/