]> git.lizzy.rs Git - dragonfireclient.git/blob - src/util/hex.h
Add function to get server info.
[dragonfireclient.git] / src / util / hex.h
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 #ifndef HEX_HEADER
21 #define HEX_HEADER
22
23 #include <string>
24
25 static const char hex_chars[] = "0123456789abcdef";
26
27 static inline std::string hex_encode(const char *data, unsigned int data_size)
28 {
29         std::string ret;
30         char buf2[3];
31         buf2[2] = '\0';
32
33         for (unsigned int i = 0; i < data_size; i++) {
34                 unsigned char c = (unsigned char)data[i];
35                 buf2[0] = hex_chars[(c & 0xf0) >> 4];
36                 buf2[1] = hex_chars[c & 0x0f];
37                 ret.append(buf2);
38         }
39
40         return ret;
41 }
42
43 static inline std::string hex_encode(const std::string &data)
44 {
45         return hex_encode(data.c_str(), data.size());
46 }
47
48 static inline bool hex_digit_decode(char hexdigit, unsigned char &value)
49 {
50         if (hexdigit >= '0' && hexdigit <= '9')
51                 value = hexdigit - '0';
52         else if (hexdigit >= 'A' && hexdigit <= 'F')
53                 value = hexdigit - 'A' + 10;
54         else if (hexdigit >= 'a' && hexdigit <= 'f')
55                 value = hexdigit - 'a' + 10;
56         else
57                 return false;
58         return true;
59 }
60
61 #endif