1 |
// Represent |
2 |
// |
3 |
// Douglas Thrift |
4 |
// |
5 |
// $Id$ |
6 |
|
7 |
#include "Hexadecimal.hpp" |
8 |
|
9 |
Hexadecimal::Hexadecimal(const ext::String& string, bool signed_) : Binary(string.GetSize() / 2, 0) |
10 |
{ |
11 |
if (string.IsEmpty()) |
12 |
{ |
13 |
bytes.InsertLast(0); |
14 |
|
15 |
return; |
16 |
} |
17 |
|
18 |
size_t index(string.GetSize() % 2), offset(index); |
19 |
|
20 |
_rforeach (ext::Vector<byte_t>, byte, bytes) _rfor (byte_t, half, 0, 2) *byte |= hex(string[index++]) << half * 4; |
21 |
|
22 |
if (offset != 0) |
23 |
{ |
24 |
bytes.InsertLast(0); |
25 |
|
26 |
bytes.Last() |= hex(string[0]); |
27 |
bytes.Last() |= signed_ && bytes.Last() > 7 ? 0xF0 : 0; |
28 |
} |
29 |
} |
30 |
|
31 |
Hexadecimal::operator ext::String() const |
32 |
{ |
33 |
ext::String string; |
34 |
|
35 |
_rforeach (const ext::Vector<byte_t>, byte, bytes) _rfor (byte_t, half, 0, 2) |
36 |
{ |
37 |
byte_t hex(0xF & *byte >> half * 4); |
38 |
|
39 |
if (hex < 0xA) hex += '0'; else hex += 'A' - 0xA; |
40 |
|
41 |
string.InsertLast(hex); |
42 |
} |
43 |
|
44 |
return string; |
45 |
} |
46 |
|
47 |
inline byte_t Hexadecimal::hex(const ext::CodePoint& atom) |
48 |
{ |
49 |
if (atom >= '0' && atom <= '9') return atom - '0'; else if (atom >= 'a' && atom <= 'f') return atom - 'a' + 0xA; else if (atom >= 'A' && atom <= 'F') return atom - 'A' + 0xA; else return 0; |
50 |
} |