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
60 lines
1.8 KiB
#include <iostream>
|
|
#include <iomanip>
|
|
#include <sstream>
|
|
|
|
// 函数:格式化内存并存储到 string 中
|
|
std::string format_memory(const void* ptr, size_t size) {
|
|
std::ostringstream oss;
|
|
const unsigned char* buffer = static_cast<const unsigned char*>(ptr);
|
|
const size_t bytes_per_line = 16;
|
|
|
|
for (size_t i = 0; i < size; i += bytes_per_line) {
|
|
// 格式化地址
|
|
oss << std::hex << std::setw(8) << std::setfill('0') << i << ": ";
|
|
|
|
// 格式化每一行的内容
|
|
for (size_t j = 0; j < bytes_per_line; ++j) {
|
|
if (i + j < size) {
|
|
// 格式化字节的十六进制值
|
|
oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(buffer[i + j]) << " ";
|
|
} else {
|
|
// 对于填充空白处
|
|
oss << " ";
|
|
}
|
|
|
|
// 格式化可打印字符,非打印字符用'.'表示
|
|
if (j == (bytes_per_line / 2) - 1) {
|
|
oss << " ";
|
|
}
|
|
}
|
|
|
|
oss << " ";
|
|
|
|
// 格式化每一行的可打印字符
|
|
for (size_t j = 0; j < bytes_per_line; ++j) {
|
|
if (i + j < size) {
|
|
char c = buffer[i + j];
|
|
// 判断是否为可打印字符
|
|
if (c >= 32 && c <= 126) {
|
|
oss << c;
|
|
} else {
|
|
oss << ".";
|
|
}
|
|
} else {
|
|
// 对于填充空白处
|
|
oss << " ";
|
|
}
|
|
}
|
|
|
|
oss << std::endl;
|
|
}
|
|
|
|
return oss.str();
|
|
}
|
|
|
|
int main() {
|
|
int array[] = {1, 2, 3, 4, 5};
|
|
std::string formatted_memory = format_memory(array, sizeof(array));
|
|
std::cout << formatted_memory << std::endl;
|
|
return 0;
|
|
}
|