A Discrete-Event Network Simulator
API
encode-decode.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2009 University of Washington
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation;
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */
18 
19 #include <string>
20 #include <iostream>
21 #include <iomanip>
22 #include <sstream>
23 #include <stdint.h>
24 
25 namespace ns3 {
26 
36 std::string
37 BufferToString (uint8_t *buffer, uint32_t len)
38 {
39  std::ostringstream oss;
40  //
41  // Tell the stream to make hex characters, zero-filled
42  //
43  oss.setf (std::ios::hex, std::ios::basefield);
44  oss.fill ('0');
45 
46  //
47  // Loop through the buffer, separating the two-digit-wide hex bytes
48  // with a colon.
49  //
50  for (uint8_t i = 0; i < len; i++)
51  {
52  oss << ":" << std::setw (2) << (uint32_t)buffer[i];
53  }
54  return oss.str ();
55 }
56 
66 bool
67 StringToBuffer (std::string s, uint8_t *buffer, uint32_t *len)
68 {
69  //
70  // If the string was made by our inverse function, the string length must
71  // be a multiple of three characters in length. Use this fact to do a
72  // quick reasonableness test.
73  //
74  if ((s.length () % 3) != 0)
75  {
76  return false;
77  }
78 
79  std::istringstream iss;
80  iss.str (s);
81 
82  uint8_t n = 0;
83 
84  while (iss.good ())
85  {
86  //
87  // The first character in the "triplet" we're working on is always the
88  // the ':' separator. Read that into a char and make sure we're skipping
89  // what we think we're skipping.
90  //
91  char c;
92  iss.read (&c, 1);
93  if (c != ':')
94  {
95  return false;
96  }
97 
98  //
99  // And then read in the real bits and convert them.
100  //
101  uint32_t tmp;
102  iss >> std::hex >> tmp;
103  buffer[n] = tmp;
104  n++;
105  }
106 
107  *len = n;
108  return true;
109 }
110 
111 } // namespace ns3
std::string BufferToString(uint8_t *buffer, uint32_t len)
Convert a byte buffer to a string containing a hex representation of the buffer.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
bool StringToBuffer(std::string s, uint8_t *buffer, uint32_t *len)
Convert string encoded by the inverse function (TapBufferToString) back into a byte buffer...