Luanti 5.15.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
12[[nodiscard]]
13static inline std::string hex_encode(std::string_view data)
14{
15 std::string ret;
16 ret.reserve(data.size() * 2);
17 for (unsigned char c : data) {
18 ret.push_back(hex_chars[(c & 0xf0) >> 4]);
19 ret.push_back(hex_chars[c & 0x0f]);
20 }
21 return ret;
22}
23
24[[nodiscard]]
25static inline std::string hex_encode(const char *data, size_t data_size)
26{
27 if (!data_size)
28 return "";
29 return hex_encode(std::string_view(data, data_size));
30}
31
32static inline bool hex_digit_decode(char hexdigit, unsigned char &value)
33{
34 if (hexdigit >= '0' && hexdigit <= '9')
35 value = hexdigit - '0';
36 else if (hexdigit >= 'A' && hexdigit <= 'F')
37 value = hexdigit - 'A' + 10;
38 else if (hexdigit >= 'a' && hexdigit <= 'f')
39 value = hexdigit - 'a' + 10;
40 else
41 return false;
42 return true;
43}
static bool hex_digit_decode(char hexdigit, unsigned char &value)
Definition hex.h:32
static const char hex_chars[]
Definition hex.h:10
static std::string hex_encode(std::string_view data)
Definition hex.h:13