Minetest  5.4.0
hex.h
Go to the documentation of this file.
1 /*
2 Minetest
3 Copyright (C) 2013 Jonathan Neuschäfer <j.neuschaefer@gmx.net>
4 
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9 
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
14 
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 
20 #pragma once
21 
22 #include <string>
23 
24 static const char hex_chars[] = "0123456789abcdef";
25 
26 static inline std::string hex_encode(const char *data, unsigned int data_size)
27 {
28  std::string ret;
29  ret.reserve(data_size * 2);
30 
31  char buf2[3];
32  buf2[2] = '\0';
33 
34  for (unsigned int i = 0; i < data_size; i++) {
35  unsigned char c = (unsigned char)data[i];
36  buf2[0] = hex_chars[(c & 0xf0) >> 4];
37  buf2[1] = hex_chars[c & 0x0f];
38  ret.append(buf2);
39  }
40 
41  return ret;
42 }
43 
44 static inline std::string hex_encode(const std::string &data)
45 {
46  return hex_encode(data.c_str(), data.size());
47 }
48 
49 static inline bool hex_digit_decode(char hexdigit, unsigned char &value)
50 {
51  if (hexdigit >= '0' && hexdigit <= '9')
52  value = hexdigit - '0';
53  else if (hexdigit >= 'A' && hexdigit <= 'F')
54  value = hexdigit - 'A' + 10;
55  else if (hexdigit >= 'a' && hexdigit <= 'f')
56  value = hexdigit - 'a' + 10;
57  else
58  return false;
59  return true;
60 }
static bool hex_digit_decode(char hexdigit, unsigned char &value)
Definition: hex.h:49
static std::string hex_encode(const char *data, unsigned int data_size)
Definition: hex.h:26
static const char hex_chars[]
Definition: hex.h:24