打印内存内容

https://stackoverflow.com/questions/2376915/how-to-print-out-the-memory-contents-of-a-variable-in-c

#include <stdio.h>
#include <string.h>

#include <iostream>

int main()
{
  double d = 234.5;

  /* 1. use a union */
  union u
  {
    double d;
    unsigned char c[sizeof(double)];
  };
  union u tmp;
  size_t i;
  tmp.d = d;
  for (i = 0; i < sizeof(double); ++i)
  {
    printf("%02x\n", tmp.c[i]);
  }
  std::cout << std::endl;

  /* 2. memcpy */
  unsigned char data[sizeof d];
  memcpy(data, &d, sizeof d);
  for (i = 0; i < sizeof d; ++i)
  {
    printf("%02x\n", data[i]);
  }

  std::cout << std::endl;
  /* 3. Use a pointer to an unsigned char to examine the bytes */
  unsigned char *p = (unsigned char *)&d;
  for (i = 0; i < sizeof d; ++i)
  {
    printf("%02x\n", p[i]);
  }

  return 0;
}

  

posted @ 2020-09-01 00:29  upupon  阅读(209)  评论(0编辑  收藏  举报