mirror of
https://github.com/djhackersdev/saltytools.git
synced 2026-04-26 01:45:29 -05:00
feat(util): add hex_encode_*() functions
This commit is contained in:
parent
4e8bf46ebf
commit
c3da699f84
48
util/hex.c
Normal file
48
util/hex.c
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
#include <assert.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
static int hex_encode(char **out, const void *ptr, size_t nbytes,
|
||||||
|
const char *digits) {
|
||||||
|
const uint8_t *bytes;
|
||||||
|
char *chars;
|
||||||
|
size_t i;
|
||||||
|
|
||||||
|
assert(out != NULL);
|
||||||
|
assert(ptr != NULL);
|
||||||
|
assert(digits != NULL);
|
||||||
|
|
||||||
|
*out = NULL;
|
||||||
|
bytes = ptr;
|
||||||
|
|
||||||
|
chars = malloc(2 * nbytes + 1);
|
||||||
|
|
||||||
|
if (chars == NULL) {
|
||||||
|
return -ENOMEM;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (i = 0; i < nbytes; i++) {
|
||||||
|
chars[i * 2 + 0] = digits[bytes[i] >> 4];
|
||||||
|
chars[i * 2 + 1] = digits[bytes[i] & 15];
|
||||||
|
}
|
||||||
|
|
||||||
|
chars[nbytes * 2] = '\0';
|
||||||
|
*out = chars;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int hex_encode_lc(char **out, const void *bytes, size_t nbytes) {
|
||||||
|
assert(out != NULL);
|
||||||
|
assert(bytes != NULL);
|
||||||
|
|
||||||
|
return hex_encode(out, bytes, nbytes, "0123456789abcdef");
|
||||||
|
}
|
||||||
|
|
||||||
|
int hex_encode_uc(char **out, const void *bytes, size_t nbytes) {
|
||||||
|
assert(out != NULL);
|
||||||
|
assert(bytes != NULL);
|
||||||
|
|
||||||
|
return hex_encode(out, bytes, nbytes, "0123456789ABCDEF");
|
||||||
|
}
|
||||||
6
util/hex.h
Normal file
6
util/hex.h
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
int hex_encode_lc(char **out, const void *bytes, size_t nbytes);
|
||||||
|
int hex_encode_uc(char **out, const void *bytes, size_t nbytes);
|
||||||
|
|
@ -8,6 +8,8 @@ util_lib = static_library(
|
||||||
'crypto.h',
|
'crypto.h',
|
||||||
'fs.c',
|
'fs.c',
|
||||||
'fs.h',
|
'fs.h',
|
||||||
|
'hex.c',
|
||||||
|
'hex.h',
|
||||||
'iobuf.c',
|
'iobuf.c',
|
||||||
'iobuf.h',
|
'iobuf.h',
|
||||||
'list.c',
|
'list.c',
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user