Bitcoin Core  27.99.0
P2P Digital Currency
uint256.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <uint256.h>
7 
8 #include <util/strencodings.h>
9 
10 template <unsigned int BITS>
11 std::string base_blob<BITS>::GetHex() const
12 {
13  uint8_t m_data_rev[WIDTH];
14  for (int i = 0; i < WIDTH; ++i) {
15  m_data_rev[i] = m_data[WIDTH - 1 - i];
16  }
17  return HexStr(m_data_rev);
18 }
19 
20 template <unsigned int BITS>
21 void base_blob<BITS>::SetHex(const char* psz)
22 {
23  std::fill(m_data.begin(), m_data.end(), 0);
24 
25  // skip leading spaces
26  while (IsSpace(*psz))
27  psz++;
28 
29  // skip 0x
30  if (psz[0] == '0' && ToLower(psz[1]) == 'x')
31  psz += 2;
32 
33  // hex string to uint
34  size_t digits = 0;
35  while (::HexDigit(psz[digits]) != -1)
36  digits++;
37  unsigned char* p1 = m_data.data();
38  unsigned char* pend = p1 + WIDTH;
39  while (digits > 0 && p1 < pend) {
40  *p1 = ::HexDigit(psz[--digits]);
41  if (digits > 0) {
42  *p1 |= ((unsigned char)::HexDigit(psz[--digits]) << 4);
43  p1++;
44  }
45  }
46 }
47 
48 template <unsigned int BITS>
49 void base_blob<BITS>::SetHex(const std::string& str)
50 {
51  SetHex(str.c_str());
52 }
53 
54 template <unsigned int BITS>
55 std::string base_blob<BITS>::ToString() const
56 {
57  return (GetHex());
58 }
59 
60 // Explicit instantiations for base_blob<160>
61 template std::string base_blob<160>::GetHex() const;
62 template std::string base_blob<160>::ToString() const;
63 template void base_blob<160>::SetHex(const char*);
64 template void base_blob<160>::SetHex(const std::string&);
65 
66 // Explicit instantiations for base_blob<256>
67 template std::string base_blob<256>::GetHex() const;
68 template std::string base_blob<256>::ToString() const;
69 template void base_blob<256>::SetHex(const char*);
70 template void base_blob<256>::SetHex(const std::string&);
71 
72 const uint256 uint256::ZERO(0);
73 const uint256 uint256::ONE(1);
void SetHex(const char *psz)
Definition: uint256.cpp:21
std::string ToString() const
Definition: uint256.cpp:55
std::string GetHex() const
Definition: uint256.cpp:11
256-bit opaque blob.
Definition: uint256.h:106
static const uint256 ONE
Definition: uint256.h:112
static const uint256 ZERO
Definition: uint256.h:111
constexpr bool IsSpace(char c) noexcept
Tests if the given character is a whitespace character.
Definition: strencodings.h:168
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
signed char HexDigit(char c)
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.