Welcome to mirror list, hosted at ThFree Co, Russian Federation.

hex.hpp « coding - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 22a82af389616ad5628144addc3abb34c00b4d7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#pragma once

#include "../base/base.hpp"
#include "../base/assert.hpp"

#include "../std/string.hpp"

#include <boost/type_traits/is_integral.hpp>

namespace impl {
  void ToHexRaw(void const * src, size_t size, void * dst);
  void FromHexRaw(void const * src, size_t size, void * dst);
}

inline string ToHex(const void * ptr, size_t size)
{
  string result;
  if (size == 0) return result;

  result.resize(size * 2);
  ::impl::ToHexRaw(ptr, size, &result[0]);

  return result;
}

template <typename ContainerT>
inline string ToHex(ContainerT const & container)
{
  STATIC_ASSERT(sizeof(*container.begin()) == 1);
  ASSERT ( !container.empty(), ("Dereference of container::end() is illegal") );

  return ToHex(&*container.begin(), container.end() - container.begin());
}

template <typename IntT>
inline string NumToHex(IntT n)
{
  STATIC_ASSERT(boost::is_integral<IntT>::value);

  uint8_t buf[sizeof(n)];

  for (size_t i = 0; i < sizeof(n); ++i)
  {
    buf[i] = (n >> ((sizeof(n) - 1) * 8));
    n <<= 8;
  }

  return ToHex(buf, sizeof(buf));
}

/// Specialization to avoid warnings
template <>
inline string NumToHex<char>(char c)
{
  return ToHex(&c, sizeof(c));
}

inline string FromHex(void const * ptr, size_t size) {
  string result;
  result.resize(size / 2);
  ::impl::FromHexRaw(ptr, size, &result[0]);
  return result;
}

inline string FromHex(string const & src) {
  return FromHex(src.c_str(), src.size());
}

inline string ByteToQuat(uint8_t n)
{
  string result;
  for (size_t i = 0; i < 4; ++i)
  {
    result += char(((n & 0xC0) >> 6) + '0');
    n <<= 2;
  }
  return result;
}

template <typename IntT>
inline string NumToQuat(IntT n)
{
  string result;
  for (size_t i = 0; i < sizeof(n); ++i)
  {
    uint8_t ub = n >> (sizeof(n) * 8 - 8);
    result += ByteToQuat(ub);
    n <<= 8;
  }
  return result;
}