C/C++ でバイトを視覚化する方法

このような関数を使用して、バイトを出力できます:

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");
}

たとえば、次のように使用します:

int x = 37;
float y = 3.14;

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

これは、このような「メモリ ダンプ」に一般的に使用される 16 進数で、生の数値としてバイトを表示します。

「Intel(R) Xeon(R)」CPU を実行している任意の (私が知る限り、仮想かもしれない) Linux マシンでは、次のように表示されます。

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

これは、Intel ファミリーの CPU:s が本当にリトル エンディアンであることも簡単に示しています。


gcc と X を使用している場合は、DDD デバッガーを使用して、データ構造のきれいな図を描画できます。


完全を期すために、C++ の例:

#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);
}