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'));

加上& 0xf.

编译器来处理:

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

完成
*/
posted @   zjh6  阅读(15)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示