[ create a new paste ] login | about

Link: http://codepad.org/trVz9mlQ    [ raw code | output | fork | 2 comments ]

RogerPate - C++, pasted on Mar 4:
#include <iomanip>
#include <ostream>
#include <string>

struct hexdump {
  void const* data;
  int len;

  hexdump(void const* data, int len) : data(data), len(len) {}

  template<class T>
  hexdump(T const& v) : data(&v), len(sizeof v) {}

  friend
  std::ostream& operator<<(std::ostream& s, hexdump const& v) {
    // don't change formatting for s
    std::ostream out (s.rdbuf());
    out << std::hex << std::setfill('0');

    unsigned char const* pc = reinterpret_cast<unsigned char const*>(v.data);

    std::string buf;
    buf.reserve(17); // premature optimization

    int i;
    for (i = 0; i < v.len; ++i, ++pc) {
      if ((i % 16) == 0) {
        if (i) {
          out << "  " << buf << '\n';
          buf.clear();
        }
        out << "  " << std::setw(4) << i << ' ';
      }

      out << ' ' << std::setw(2) << unsigned(*pc);
      buf += (0x20 <= *pc && *pc <= 0x7e) ? *pc : '.';
    }
    if (i % 16) {
      char const* spaces16x3 = "                                                ";
      out << &spaces16x3[3 * (i % 16)];
    }
    out << "  " << buf << '\n';

    return s;
  }
};

int main() {
  cout << "double:\n" << hexdump(234.5);
  cout << "string 1:\n" << hexdump("a 15char string");
  cout << "string 2:\n" << hexdump("This is a slightly longer string");

  return 0;
}


Output:
1
2
3
4
5
6
7
8
double:
  0000  00 00 00 00 00 50 6d 40                          .....Pm@
string 1:
  0000  61 20 31 35 63 68 61 72 20 73 74 72 69 6e 67 00  a 15char string.
string 2:
  0000  54 68 69 73 20 69 73 20 61 20 73 6c 69 67 68 74  This is a slight
  0010  6c 79 20 6c 6f 6e 67 65 72 20 73 74 72 69 6e 67  ly longer string
  0020  00                                               .


Create a new paste based on this one


Comments:
posted by RogerPate on Mar 4
reply
posted by RogerPate on Mar 4
I place this code in the public domain. If it breaks, you get to keep both pieces.
reply