add hex_to_str

This commit is contained in:
Evan Burkey 2024-03-29 07:18:01 -07:00
parent f60bea0fdd
commit 0408b8d499
4 changed files with 28 additions and 0 deletions

View File

@ -56,4 +56,13 @@ for (size_t i = 0; i < 4; ++i) {
assert(s[i] == h[i]);
}
free(s);
```
### hex_to_str
Converts an array of `unsigned char` into a string based on the ASCII values of each byte. User is
responsible for freeing the returned string.
```c
const char *hex_to_str(const unsigned char *hex, size_t sz);
```

View File

@ -5,7 +5,9 @@
const char *b64_encode(const unsigned char *s, size_t sz);
unsigned char *b64_decode(const char *s, size_t sz, size_t *decode_sz);
const char *hex_encode(const unsigned char *hex, size_t sz);
unsigned char *hex_decode(const char *orig, size_t *sz);
const char *hex_to_str(const unsigned char *hex, size_t sz);
#endif // LIBFLINT_CRYPTO_H

View File

@ -243,3 +243,12 @@ const char *hex_encode(const unsigned char *hex, size_t sz) {
return s;
}
const char *hex_to_str(const unsigned char *hex, size_t sz) {
char *s = malloc(sizeof(char) * (sz + 1));
for (size_t i = 0; i < sz; ++i) {
s[i] = (char)hex[i];
}
s[sz] = '\0';
return s;
}

View File

@ -349,6 +349,14 @@ void test_crypto() {
s = hex_encode(h, 4);
assert(strcmp(s, "DEADBEEF") == 0);
free(s);
// "Sup?"
unsigned char hexsup[4] = {
0x53, 0x75, 0x70, 0x3F
};
s = hex_to_str(hexsup, 4);
assert(strcmp(s, "Sup?") == 0);
free(s);
}
#if defined(__APPLE__) || defined(__MACH__)