11

I'm working my way through some C++ training. So far so good, but I need some help reinforcing some of the concepts I am learning. My question is how do I go about visualizing the byte patterns for objects I create. For example, how would I print out the byte pattern for structs, longs, ints etc?

I understand it in my head and can understand the diagrams in my study materials, I'd just like to be able to programaticially display byte patterns from within some of my study programs.

I realize this is pretty trivial but any answers would greatly help me hammer in these concepts.

Thanks.

Edit: I use mostly XCode for my other development projects, but have VMs for Windows7 and fedora core. At work I use XP with visual studio 2005. ( I can't comment as I am still a n00b here :D)

I used unwind's solution which is about what I am looking for. I am also thinking that maybe I could just use the dos DEBUG command as I'd also like to look at chunks for memory too. Again, this is just to help me reinforce what I am learning. Thanks again people!

3
  • You need to explain yourt environment (compiler, debugger if oyu have one, OS etc.) May 28, 2009 at 12:00
  • Do you mean debugger info so you can see your loaded object in memory during runtime?
    – Dewm Solo
    May 28, 2009 at 12:31
  • Yes, debugger info would be grand.
    – OhioDude
    May 28, 2009 at 13:17

7 Answers 7

26

You can use a function such as this, to print the bytes:

static void print_bytes(const void *object, size_t size)
{
#ifdef __cplusplus
  const unsigned char * const bytes = static_cast<const unsigned char *>(object);
#else // __cplusplus
  const unsigned char * const bytes = object;
#endif // __cplusplus

  size_t i;

  printf("[ ");
  for(i = 0; i < size; i++)
  {
    printf("%02x ", bytes[i]);
  }
  printf("]\n");
}

Usage would look like this, for instance:

int x = 37;
float y = 3.14;

print_bytes(&x, sizeof x);
print_bytes(&y, sizeof y);

This shows the bytes just as raw numerical values, in hexadecimal which is commonly used for "memory dumps" like these.

On a random (might even be virtual, for all I know) Linux machine running a "Intel(R) Xeon(R)" CPU, this prints:

[ 25 00 00 00 ]
[ c3 f5 48 40 ]

This handily also demonstrates that the Intel family of CPU:s really are little endian.

4
  • @user1721803 Because you can't dereference void *'. I think it's cleaner to have a function like this accept a const void `, since that makes *using the function very simple and cast-less. Casts are to be avoided, much better to contain them where needed instead of inflicting them on others.
    – unwind
    Nov 22, 2014 at 16:51
  • @unwind why do you do that bitwise and of each byte with 0xff ? Is it necessary? May 15, 2016 at 12:27
  • @JoãoAlmeida No, it shouldn't really be. Just kind of belt-and-suspenders thinking, I guess. Which is something I dislike, so I'll edit that out now. Thanks.
    – unwind
    May 16, 2016 at 10:55
  • error: invalid conversion from ‘const void*’ to ‘const unsigned char*’ [-fpermissive] const unsigned char * const bytes = object;
    – NDEthos
    Jun 19, 2017 at 7:05
6

If you are using gcc and X, you can use the DDD debugger to draw pretty pictures of your data structures for you.

1
  • DDD actually has very good visualization. it's great when you want to see a complex data structure. Heck, even a linked list is nice in DDD. May 28, 2009 at 13:23
6

Just for completeness, a C++ example:

#include <iostream>

template <typename T>
void print_bytes(const T& input, std::ostream& os = std::cout)
{
  const unsigned char* p = reinterpret_cast<const unsigned char*>(&input);
  os << std::hex << std::showbase;
  os << "[";
  for (unsigned int i=0; i<sizeof(T); ++i)
    os << static_cast<int>(*(p++)) << " ";
  os << "]" << std::endl;;
}

int main()
{
  int i = 12345678;
  print_bytes(i);
  float x = 3.14f;
  print_bytes(x);
}
2

Or if you have the boost lib and want to use lambda evaluations you can do it this way ...

template<class T>
void bytePattern( const T& object )
{
    typedef unsigned char byte_type;
    typedef const byte_type* iterator;

    std::cout << "Object type:" << typeid( T ).name() << std::hex;
    std::for_each( 
        reinterpret_cast<iterator>(&object), 
        reinterpret_cast<iterator>(&object) + sizeof(T), 
        std::cout << constant(' ') << ll_static_cast<int>(_1 )&&0xFF );   
    std::cout << "\n";
}
1
  • You've not mentioned what bits of your example come from Boost.Lambda, what may be difficult to decode by not experienced programmers. Here we go: boost::lambda::ll_static_cast, boost::lambda::_1
    – mloskot
    Feb 5, 2010 at 22:40
2

Most (visual) debuggers have a "View Memory' option. IIRC the one in Xcode is pretty basic, just showing bytes in HEX and ASCII, with a variable line length. Visual Studio (Debug->Windows->Memory in Vs2008) can format the hex portion as different integer lengths, or floating point, change the endianess, and display ANSI or UNICODE text. You can also set just about any number for the width of the window (I think xcode only lets you go to 64 bytes wide) The other IDE I have here at work has a lot of options, though not quite as many as VS.

0

A little bit by bit console program i whipped up, hope it helps somebody

#include <iostream>
#include <inttypes.h>
#include <vector>
using namespace std;
typedef  vector<uint8_t> ByteVector;
///////////////////////////////////////////////////////////////
uint8_t Flags[8] = { 0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
void print_bytes(ByteVector Bv){
    for (unsigned i = 0; i < Bv.size(); i++){
        printf("Byte %d [ ",i);
        for (int j  = 0;j < 8;++j){
            Bv[i] & Flags[j] ? printf("1") : printf("0");
        }
        printf("]\n");
    }
}
int main(){
    ByteVector Bv;
    for (int i = 0; i < 4; ++i) { Bv.push_back(i); }
    print_bytes(Bv);
}
-2

try this:

MyClass* myObj = new MyClass();
int size=sizeof(*myObj);
int i;
char* ptr = obj; // closest approximation to byte
for( i=0; i<size; i++ )
    std::cout << *ptr << endl;

Cheers,

jrh.

2
  • char * ptr = reinterpret_cast <char*> (myObj );
    – anon
    May 28, 2009 at 12:28
  • and probably endl needs a std:: prefix
    – none
    May 29, 2009 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.