1 // Copyright (c) 2014-2017 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.
5 #ifndef BITCOIN_CRYPTO_COMMON_H
6 #define BITCOIN_CRYPTO_COMMON_H
8 #if defined(HAVE_CONFIG_H)
9 #include <config/bitcoin-config.h>
15 #include <compat/endian.h>
17 uint16_t static inline ReadLE16(const unsigned char* ptr
)
20 memcpy((char*)&x
, ptr
, 2);
24 uint32_t static inline ReadLE32(const unsigned char* ptr
)
27 memcpy((char*)&x
, ptr
, 4);
31 uint64_t static inline ReadLE64(const unsigned char* ptr
)
34 memcpy((char*)&x
, ptr
, 8);
38 void static inline WriteLE16(unsigned char* ptr
, uint16_t x
)
40 uint16_t v
= htole16(x
);
41 memcpy(ptr
, (char*)&v
, 2);
44 void static inline WriteLE32(unsigned char* ptr
, uint32_t x
)
46 uint32_t v
= htole32(x
);
47 memcpy(ptr
, (char*)&v
, 4);
50 void static inline WriteLE64(unsigned char* ptr
, uint64_t x
)
52 uint64_t v
= htole64(x
);
53 memcpy(ptr
, (char*)&v
, 8);
56 uint32_t static inline ReadBE32(const unsigned char* ptr
)
59 memcpy((char*)&x
, ptr
, 4);
63 uint64_t static inline ReadBE64(const unsigned char* ptr
)
66 memcpy((char*)&x
, ptr
, 8);
70 void static inline WriteBE32(unsigned char* ptr
, uint32_t x
)
72 uint32_t v
= htobe32(x
);
73 memcpy(ptr
, (char*)&v
, 4);
76 void static inline WriteBE64(unsigned char* ptr
, uint64_t x
)
78 uint64_t v
= htobe64(x
);
79 memcpy(ptr
, (char*)&v
, 8);
82 /** Return the smallest number n such that (x >> n) == 0 (or 64 if the highest bit in x is set. */
83 uint64_t static inline CountBits(uint64_t x
)
85 #ifdef HAVE_DECL___BUILTIN_CLZL
86 if (sizeof(unsigned long) >= sizeof(uint64_t)) {
87 return x
? 8 * sizeof(unsigned long) - __builtin_clzl(x
) : 0;
90 #ifdef HAVE_DECL___BUILTIN_CLZLL
91 if (sizeof(unsigned long long) >= sizeof(uint64_t)) {
92 return x
? 8 * sizeof(unsigned long long) - __builtin_clzll(x
) : 0;
103 #endif // BITCOIN_CRYPTO_COMMON_H