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!
You can use a function such as this, to print the bytes:
void print_bytes(const void *object, size_t size)
{
// This is for C++; in C just drop the static_cast<>() and assign.
const unsigned char * const bytes = static_cast<const unsigned char *>(object);
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.
@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 why do you do that bitwise and of each byte with
0xff
? Is it necessary?@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.
error: invalid conversion from ‘const void*’ to ‘const unsigned char*’ [-fpermissive] const unsigned char * const bytes = object;