On Thursday, 26 September 2024 at 06:53:12 UTC, Per Nordlöw wrote:
Should a function like
```d
uint parseHex(in char ch) pure nothrow @safe @nogc {
switch (ch) {
case '0': .. case '9':
return ch - '0';
case 'a': .. case 'f':
return 10 + ch - 'a';
case 'A': .. case 'F':
return 10 + ch - 'A';
default:
assert(0, "Non-hexadecimal character");
}
}
```
instead return an ubyte?
When I use standard library facilities, I try to use ubyte; for
example:
(See "toggle comment" in the section...)
```d
void parseFromHexString(R)(out R hex, const(char)[] str)
{
import std.algorithm : map, copy;
import std.conv : to;
import std.range : front, chunks;
alias T = typeof(hex.front);
str.chunks(T.sizeof * 2)
.map!(bin => bin
.to!T(16))
.copy(hex[]);
}
import std.stdio;
void main()
{
enum hex = "48656C6C6F2044202620576F726C6421";
enum size = hex.length / 2;
auto sample = imported!"std.conv".hexString!hex;
sample.writeln; // Hello D & World!
enum hexStr = x"48656C6C6F2044202620576F726C6421";
hexStr.writeln; // Hello D & World!
assert(is(typeof(hexStr) == string));
immutable int[] intStr = x"48656C6C6F2044202620576F726C6421";
intStr.writeln; // [1214606444, 1864385568, 639653743,
1919706145]
int[size] buf;
buf.parseFromHexString(hex);
buf.writeln;
//char[size] buff; /*
ubyte[size] buff;/* please toggle comment with above */
buff.parseFromHexString("BADEDE");
buff.writeln;
```
But when I try to do something with my own functions, I have
control and I do what I want. You can also use char below, ubyte
is not a problem either:
```d
auto toHexDigit(char value)
{
if(value > 9) value += 7;
return '0' + value;
}
auto toHexString(R)(R str)
{
string result;
char a, b;
foreach(char c; str)
{
a = c / 16; b = c % 16;
result ~= a.toHexDigit;
result ~= b.toHexDigit;
}
return result;
}
void main() { assert(sample.toHexString == hex); }
```
SDB@79