Subversion Repositories HomeAutomation

Rev

Rev 1647 | Rev 1684 | Go to most recent revision | Show entire file | Regard whitespace | Details | Blame | Last modification | View Log | SVN | RSS feed

Rev 1647 Rev 1657
Line 17... Line 17...
17
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
 *
18
 *
19
 */
19
 */
20
 
20
 
21
#include "common.h"
21
#include "common.h"
-
 
22
 
-
 
23
#include <iostream>
22
 
24
 
23
namespace atom {
25
namespace atom {
24
namespace common {
26
namespace common {
25
 
27
 
26
std::string PadNumber(unsigned int number, unsigned int length)
28
std::string PadNumber(unsigned int number, unsigned int length)
27
{
29
{
28
    std::string padded_string = boost::lexical_cast<std::string>(number);
30
    std::string padded_string = boost::lexical_cast<std::string>(number);
29
   
31
   
30
    while (padded_string.length() < length)
32
    while (padded_string.length() < length)
Line 34... Line 36...
34
   
36
   
35
    return padded_string;
37
    return padded_string;
36
}
38
}
37
   
39
   
38
std::string ToHex(unsigned int value)
40
std::string ToHex(unsigned int value)
39
{
41
{
40
    char hex_string[11];
42
    char hex_string[11];
41
   
43
   
42
    snprintf(hex_string, sizeof(hex_string), "0x%08X", value);
44
    snprintf(hex_string, sizeof(hex_string), "0x%08X", value);
43
   
45
   
44
    return std::string(hex_string);
46
    return std::string(hex_string);
45
   
47
   
46
}
48
}
47
 
49
 
48
unsigned int FromHex(std::string hex_chars)
50
unsigned int FromHex(std::string hex_chars)
49
{
51
{
50
    int value = 0;
-
 
51
    int ascii_value;
-
 
52
   
-
 
53
    for (int n = hex_chars.length() - 1; n >= 0; n--)
-
 
54
    {
-
 
55
        ascii_value = (int)hex_chars.data()[n];
-
 
56
       
-
 
57
        if (48 <= ascii_value && ascii_value <= 57)
-
 
58
        {
-
 
59
            value |= (ascii_value - 48) << n;
-
 
60
        }
-
 
61
        else if (65 <= ascii_value && ascii_value <= 70)
-
 
62
        {
-
 
63
            value |= (ascii_value - 65) << n;
-
 
64
        }
-
 
65
        else
-
 
66
        {
-
 
67
            throw std::runtime_error("This is not an hex string, hex_chars = " + hex_chars + ", ascii_value = " + boost::lexical_cast<std::string>(ascii_value) + ", n = " + boost::lexical_cast<std::string>(n) + ", length = " + boost::lexical_cast<std::string>(hex_chars.length()));
52
    return static_cast<unsigned int>(strtol(hex_chars.data(), NULL, 16));
68
        }
-
 
69
    }
-
 
70
   
-
 
71
    return value;
-
 
72
}
53
}
73
   
54
   
74
}; // namespace type
55
}; // namespace type
75
}; // namespace atom
56
}; // namespace atom