Bitcoin ABC 0.32.12
P2P Digital Currency
hex_base.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <crypto/hex_base.h>
6
7#include <array>
8#include <cstdint>
9#include <cstring>
10#include <string>
11
12namespace {
13
14using ByteAsHex = std::array<char, 2>;
15
16constexpr std::array<ByteAsHex, 256> CreateByteToHexMap() {
17 constexpr char hexmap[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
18 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
19
20 std::array<ByteAsHex, 256> byte_to_hex{};
21 for (size_t i = 0; i < byte_to_hex.size(); ++i) {
22 byte_to_hex[i][0] = hexmap[i >> 4];
23 byte_to_hex[i][1] = hexmap[i & 15];
24 }
25 return byte_to_hex;
26}
27
28} // namespace
29
30std::string HexStr(const Span<const uint8_t> s) {
31 std::string rv(s.size() * 2, '\0');
32 static constexpr auto byte_to_hex = CreateByteToHexMap();
33 static_assert(sizeof(byte_to_hex) == 512);
34
35 char *it = rv.data();
36 for (uint8_t v : s) {
37 std::memcpy(it, byte_to_hex[v].data(), 2);
38 it += 2;
39 }
40
41 assert(it == rv.data() + rv.size());
42 return rv;
43}
44
45const signed char p_util_hexdigit[256] = {
46 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
47 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
48 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
49 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
50 -1, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, -1, -1, -1, -1, -1, -1, -1, -1, -1,
51 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
52 -1, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, -1, -1, -1, -1, -1, -1, -1, -1, -1,
53 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
54 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
55 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
56 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
57 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
58 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
59 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
60 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
61 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
62};
63
64signed char HexDigit(char c) {
65 return p_util_hexdigit[(uint8_t)c];
66}
constexpr std::size_t size() const noexcept
Definition: span.h:210
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
const signed char p_util_hexdigit[256]
Definition: hex_base.cpp:45
signed char HexDigit(char c)
Definition: hex_base.cpp:64
assert(!tx.IsCoinBase())