How to create a hex dump of data from memory in C++

2 Answers

0 votes
#include <iostream>
#include <iomanip>
#include <cctype>

void hexdump(void *ptr, int len) {
    unsigned char *buf = static_cast<unsigned char*>(ptr);
    
    for (int i = 0; i < len; i += 16) {
        std::cout << std::hex << std::setw(6) << std::setfill('0') << i << ": ";
        for (int j = 0; j < 16; j++) {
            if (i + j < len) {
                std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(buf[i + j]) << " ";
            } else {
                std::cout << "   ";
            }
            std::cout << " ";
        }

        for (int j = 0; j < 16; j++) {
            if (i + j < len) {
                std::cout << (std::isprint(buf[i + j]) ? (char)buf[i + j] : '.');
            }
        }
        std::cout << "\n";
    }
}

int main() {
    char arr[] = "abcdefghijklmnopqrstuvwxyzaaaaaaaaaaaaaaaaa";
    
    hexdump(arr, 43);
}


  
  
/*
run:
     
000000: 61  62  63  64  65  66  67  68  69  6a  6b  6c  6d  6e  6f  70  abcdefghijklmnop
000010: 71  72  73  74  75  76  77  78  79  7a  61  61  61  61  61  61  qrstuvwxyzaaaaaa
000020: 61  61  61  61  61  61  61  61  61  61  61                      aaaaaaaaaaa
              
*/

 



answered Dec 5, 2024 by avibootz
0 votes
#include <iostream>
#include <iomanip>
#include <cctype>
 
void hexdump(std::string str, int len) {
    for (int i = 0; i < len; i += 16) {
        std::cout << std::hex << std::setw(6) << std::setfill('0') << i << ": ";
        for (int j = 0; j < 16; j++) {
            if (i + j < len) {
                std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(str[i + j]) << " ";
            } else {
                std::cout << "   ";
            }
            std::cout << " ";
        }
 
        for (int j = 0; j < 16; j++) {
            if (i + j < len) {
                std::cout << (std::isprint(str[i + j]) ? (char)str[i + j] : '.');
            }
        }
        std::cout << "\n";
    }
}
 
int main() {
    std::string str = "abcdefghijklmnopqrstuvwxyzaaaaaaaaaaaaaaaaa";
     
    hexdump(str, 43);
}
 
 
   
   
/*
run:
      
000000: 61  62  63  64  65  66  67  68  69  6a  6b  6c  6d  6e  6f  70  abcdefghijklmnop
000010: 71  72  73  74  75  76  77  78  79  7a  61  61  61  61  61  61  qrstuvwxyzaaaaaa
000020: 61  61  61  61  61  61  61  61  61  61  61                      aaaaaaaaaaa
               
*/

 



answered Dec 5, 2024 by avibootz
...