aboutsummaryrefslogtreecommitdiff
path: root/include/odhtdb/hex2bin.hpp
blob: 96a2229e436a45ed125aa1988d1f709f98cd42e6 (plain)
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
50
51
52
53
54
55
56
57
58
59
60
#pragma once

#include <string>
#include <stdexcept>

namespace odhtdb
{
    class InvalidHexStringFormat : public std::runtime_error
    {
    public:
        InvalidHexStringFormat(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    // Returns -1 if c is not a hex string (0-9a-fA-F)
    static int __hexchar_to_num(int c)
    {
        if(c >= '0' && c <= '9')
            return c - '0';
        else if(c >= 'a' && c <= 'f')
            return 10 + (c - 'a');
        else if(c >= 'A' && c <= 'F')
            return 10 + (c - 'A');
        else
            return -1;
    }
    
    // Throws InvalidHexStringFormat on invalid input
    static std::string hex2bin(const char *data, size_t dataSize)
    {
        if(dataSize % 2 != 0)
            throw InvalidHexStringFormat("Input string size is not of an even size");
        
        std::string result;
        result.resize(dataSize / 2);
        
        for(int i = 0; i < dataSize; i += 2)
        {
            int v = __hexchar_to_num(data[i]);
            int v2 = __hexchar_to_num(data[i + 1]);
            
            if(v == -1)
            {
                std::string errMsg = "Invalid hex character: ";
                errMsg += data[i];
                throw InvalidHexStringFormat(errMsg);
            }
            
            if(v2 == -1)
            {
                std::string errMsg = "Invalid hex character: ";
                errMsg += data[i + 1];
                throw InvalidHexStringFormat(errMsg);
            }
            
            result[i / 2] = (v << 4) | v2;
        }
        
        return result;
    }
}