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
完成
*/
浙公网安备 33010602011771号