Add hex encoding/decoding

This commit is contained in:
2026-08-11 23:36:48 +02:00
parent 141220aecb
commit 86d2648cca
3 changed files with 113 additions and 1 deletions
+52
View File
@@ -93,6 +93,58 @@ S64 str_index(Str haystack, Str needle)
return -1;
}
static const char hex_chars[] = "0123456789ABCDEF";
Str str_hex_encode(Str source, Str destination)
{
Assert(destination.len >= source.len * 2);
U32 hex_len = source.len * 2;
for (U32 i = 0, t = 0; i < source.len; ++i,t+=2) {
U8 high_nibble;
U8 low_nibble;
high_nibble = (source.str[i] & 0xF0) >> 4 ;
low_nibble = source.str[i] & 0x0F ;
destination.str[t] = hex_chars[high_nibble];
destination.str[t+1] = hex_chars[low_nibble];
}
destination.len = hex_len;
return destination;
}
Str str_hex_decode(Str source, Str destination)
{
Assert(destination.len >= source.len/2);
U32 dest_pos = 0;
U32 source_pos = 0;
while (source_pos + 1 < source.len) {
if (char_is_ascii_whitespace(source.str[source_pos])) {
source_pos++;
continue;
}
S16 high_nibble;
S16 low_nibble;
high_nibble = char_hex_to_binary(source.str[source_pos]);
low_nibble = char_hex_to_binary(source.str[source_pos + 1]);
if (high_nibble == -1 || low_nibble == -1) {
destination.len = 0;
return destination;
}
destination.str[dest_pos] = (high_nibble << 4 ) | low_nibble;
source_pos += 2;
dest_pos++;
}
destination.len = dest_pos;
return destination;
}
// split @str on any byte in @separators, place split strings in @vec
void str_split(Str str, Str separators, StrVec *vec)
{