You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.8 KiB

1 year ago
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <sstream>
  4. // 函数:格式化内存并存储到 string 中
  5. std::string format_memory(const void* ptr, size_t size) {
  6. std::ostringstream oss;
  7. const unsigned char* buffer = static_cast<const unsigned char*>(ptr);
  8. const size_t bytes_per_line = 16;
  9. for (size_t i = 0; i < size; i += bytes_per_line) {
  10. // 格式化地址
  11. oss << std::hex << std::setw(8) << std::setfill('0') << i << ": ";
  12. // 格式化每一行的内容
  13. for (size_t j = 0; j < bytes_per_line; ++j) {
  14. if (i + j < size) {
  15. // 格式化字节的十六进制值
  16. oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(buffer[i + j]) << " ";
  17. } else {
  18. // 对于填充空白处
  19. oss << " ";
  20. }
  21. // 格式化可打印字符,非打印字符用'.'表示
  22. if (j == (bytes_per_line / 2) - 1) {
  23. oss << " ";
  24. }
  25. }
  26. oss << " ";
  27. // 格式化每一行的可打印字符
  28. for (size_t j = 0; j < bytes_per_line; ++j) {
  29. if (i + j < size) {
  30. char c = buffer[i + j];
  31. // 判断是否为可打印字符
  32. if (c >= 32 && c <= 126) {
  33. oss << c;
  34. } else {
  35. oss << ".";
  36. }
  37. } else {
  38. // 对于填充空白处
  39. oss << " ";
  40. }
  41. }
  42. oss << std::endl;
  43. }
  44. return oss.str();
  45. }
  46. int main() {
  47. int array[] = {1, 2, 3, 4, 5};
  48. std::string formatted_memory = format_memory(array, sizeof(array));
  49. std::cout << formatted_memory << std::endl;
  50. return 0;
  51. }