How to visualize bytes with C/C++
If you are using gcc and X, you can use the DDD debugger to draw pretty pictures of your data structures for you.
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";
}
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);
}
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.