Luanti 5.11.0-dev
 
Loading...
Searching...
No Matches
hex.h
Go to the documentation of this file.
1// Luanti
2// SPDX-License-Identifier: LGPL-2.1-or-later
3// Copyright (C) 2013 Jonathan Neuschäfer <j.neuschaefer@gmx.net>
4
5#pragma once
6
7#include <string>
8#include <string_view>
9
10static const char hex_chars[] = "0123456789abcdef";
11
12static inline std::string hex_encode(const char *data, unsigned int data_size)
13{
14 std::string ret;
15 ret.reserve(data_size * 2);
16
17 char buf2[3];
18 buf2[2] = '\0';
19
20 for (unsigned int i = 0; i < data_size; i++) {
21 unsigned char c = (unsigned char)data[i];
22 buf2[0] = hex_chars[(c & 0xf0) >> 4];
23 buf2[1] = hex_chars[c & 0x0f];
24 ret.append(buf2);
25 }
26
27 return ret;
28}
29
30static inline std::string hex_encode(std::string_view data)
31{
32 return hex_encode(data.data(), data.size());
33}
34
35static inline bool hex_digit_decode(char hexdigit, unsigned char &value)
36{
37 if (hexdigit >= '0' && hexdigit <= '9')
38 value = hexdigit - '0';
39 else if (hexdigit >= 'A' && hexdigit <= 'F')
40 value = hexdigit - 'A' + 10;
41 else if (hexdigit >= 'a' && hexdigit <= 'f')
42 value = hexdigit - 'a' + 10;
43 else
44 return false;
45 return true;
46}
static bool hex_digit_decode(char hexdigit, unsigned char &value)
Definition hex.h:35
static std::string hex_encode(const char *data, unsigned int data_size)
Definition hex.h:12
static const char hex_chars[]
Definition hex.h:10