MongoDB C++ Driver  legacy-1.0.5
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
hex.h
1 // util/hex.h
2 
3 /* Copyright 2009 10gen Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #pragma once
19 
20 #include <string>
21 
22 #include "mongo/base/string_data.h"
23 #include "mongo/bson/util/builder.h"
24 
25 namespace mongo {
26  //can't use hex namespace because it conflicts with hex iostream function
27  inline int fromHex( char c ) {
28  if ( '0' <= c && c <= '9' )
29  return c - '0';
30  if ( 'a' <= c && c <= 'f' )
31  return c - 'a' + 10;
32  if ( 'A' <= c && c <= 'F' )
33  return c - 'A' + 10;
34  verify( false );
35  return 0xff;
36  }
37  inline char fromHex( const char *c ) {
38  return (char)(( fromHex( c[ 0 ] ) << 4 ) | fromHex( c[ 1 ] ));
39  }
40  inline char fromHex( const StringData& c ) {
41  return (char)(( fromHex( c[ 0 ] ) << 4 ) | fromHex( c[ 1 ] ));
42  }
43 
44  inline std::string toHex(const void* inRaw, int len) {
45  static const char hexchars[] = "0123456789ABCDEF";
46 
47  StringBuilder out;
48  const char* in = reinterpret_cast<const char*>(inRaw);
49  for (int i=0; i<len; ++i) {
50  char c = in[i];
51  char hi = hexchars[(c & 0xF0) >> 4];
52  char lo = hexchars[(c & 0x0F)];
53 
54  out << hi << lo;
55  }
56 
57  return out.str();
58  }
59 
60  template <typename T> std::string integerToHex(T val);
61 
62  inline std::string toHexLower(const void* inRaw, int len) {
63  static const char hexchars[] = "0123456789abcdef";
64 
65  StringBuilder out;
66  const char* in = reinterpret_cast<const char*>(inRaw);
67  for (int i=0; i<len; ++i) {
68  char c = in[i];
69  char hi = hexchars[(c & 0xF0) >> 4];
70  char lo = hexchars[(c & 0x0F)];
71 
72  out << hi << lo;
73  }
74 
75  return out.str();
76  }
77 }
the main MongoDB namespace
Definition: bulk_operation_builder.h:24