aboutsummaryrefslogtreecommitdiff
path: root/hex.c
blob: 61cf55fe17da06d9ad11096911e89b7c63a32482 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "hex.h"
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int hex_encode(const void *const b, char *hex, const size_t buflen,
    size_t hexlen)
{
    const char *buf = b;

    for (size_t i = 0; i < buflen; i++)
    {
        const int r = snprintf(hex, hexlen, "%02hhx", *(const char *)buf++);

        if (r < 0 || r >= hexlen)
            return -1;

        hexlen -= r;
        hex += 2;
    }

    return 0;
}

int hex_decode(const char *const hex, void *const b, size_t n)
{
    unsigned char *buf = b;

    for (const char *s = hex; *s; s += 2)
    {
        const char nibble[sizeof "00"] = {*s, *(s + 1)};

        if (!n)
            return -1;

        char *end;

        errno = 0;
        *buf++ = strtoul(nibble, &end, 16);

        if (errno || *end)
            return -1;

        n--;
    }

    return n ? -1 : 0;
}