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
完成
*/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现