10 const char* chars
= "0123456789abcdef";
11 const char* charsu
= "0123456789abcdef";
13 std::string
to24(uint32_t data
, bool prefix
) throw(std::bad_alloc
)
15 return to
<ss_uint24_t
>(data
, prefix
);
18 std::string
b_to(const uint8_t* data
, size_t datalen
, bool uppercase
) throw(std::bad_alloc
)
20 const char* cset
= uppercase
? charsu
: chars
;
22 s
.resize(2 * datalen
);
23 for(size_t i
= 0; i
< datalen
; i
++) {
24 s
[2 * i
+ 0] = cset
[data
[i
] >> 4];
25 s
[2 * i
+ 1] = cset
[data
[i
] & 15];
30 template<typename T
> std::string
to(T data
, bool prefix
) throw(std::bad_alloc
)
32 return (stringfmt() << (prefix
? "0x" : "") << std::hex
<< std::setfill('0') << std::setw(2 * sizeof(T
))
33 << (uint64_t)data
).str();
36 void b_from(uint8_t* buf
, const std::string
& hex
) throw(std::runtime_error
)
39 throw std::runtime_error("hex::frombinary: Length of string must be even");
40 size_t len
= hex
.length();
42 unsigned char tmp
= 0;
43 for(size_t i
= 0; i
< len
; i
++) {
46 if(ch
>= '0' && ch
<= '9')
48 else if(ch
>= 'A' && ch
<= 'F')
49 tmp
+= (ch
- 'A' + 10);
50 else if(ch
>= 'a' && ch
<= 'f')
51 tmp
+= (ch
- 'a' + 10);
53 throw std::runtime_error("hex::frombinary: Bad hex character");
60 template<typename T
> T
from(const std::string
& hex
) throw(std::runtime_error
)
62 if(hex
.length() > 2 * sizeof(T
))
63 throw std::runtime_error("hex::from: Hexadecimal value too long");
65 size_t len
= hex
.length();
66 for(size_t i
= 0; i
< len
; i
++) {
69 if(ch
>= '0' && ch
<= '9')
71 else if(ch
>= 'A' && ch
<= 'F')
72 tmp
+= (ch
- 'A' + 10);
73 else if(ch
>= 'a' && ch
<= 'f')
74 tmp
+= (ch
- 'a' + 10);
76 throw std::runtime_error("hex::from<T>: Bad hex character");
81 template<typename T
> void _ref2()
83 eat_argument(from
<T
>);
94 _ref2
<unsigned int>();
95 _ref2
<unsigned long>();
96 _ref2
<unsigned long long>();
101 #ifdef TEST_HEX_ROUTINES
104 int main(int argc
, char** argv
)
106 std::cerr
<< hex::to64(100) << std::endl
;
108 std::string a1 = argv[1];
109 typedef ss_uint24_t type_t;
111 val = hex::from<type_t>(a1);
112 std::cerr << (uint64_t)val << std::endl;