Extract hex or RAW file data into text

I was wondering if there is a way to output hexdump or raw file data to a txt file. for example I have a let say file "data.jpg" (the type of the file does not matter), how can I export HEXdump (14ed 5602, etc.) to the file "output.txt"? Also how can I specify an output format like Unicode or UTF? in c ++

+3
source share
3 answers

This is pretty old - if you want Unicode, you have to add it yourself.

#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { unsigned long offset = 0; FILE *input; int bytes, i, j; unsigned char buffer[16]; char outbuffer[60]; if ( argc < 2 ) { fprintf(stderr, "\nUsage: dump filename [filename...]"); return EXIT_FAILURE; } for (j=1;j<argc; ++j) { if ( NULL ==(input=fopen(argv[j], "rb"))) continue; printf("\n%s:\n", argv[j]); while (0 < (bytes=fread(buffer, 1, 16, input))) { sprintf(outbuffer, "%8.8lx: ", offset+=16); for (i=0;i<bytes;i++) { sprintf(outbuffer+10+3*i, "%2.2X ",buffer[i]); if (!isprint(buffer[i])) buffer[i] = '.'; } printf("%-60s %*.*s\n", outbuffer, bytes, bytes, buffer); } fclose(input); } return 0; } 
+1
source

You can use a loop, fread and fprintf: With reading, you get the byte value of the bytes, then with fprintf you can use %x to print the hex file.

http://www.cplusplus.com/reference/clibrary/cstdio/fread/

http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/

If you want it to be fast, you load whole machine words (int or long long) instead of single bytes, if you want it to be even faster, you rephrase the whole array, then sprintf the whole array, then fprintf, which is the array in file.

+2
source

Maybe something like this?

 #include <sstream> #include <iostream> #include <iomanip> #include <iterator> #include <algorithm> int main() { std::stringstream buffer( "testxzy" ); std::istreambuf_iterator<char> it( buffer.rdbuf( ) ); std::istreambuf_iterator<char> end; // eof std::cout << std::hex << std::showbase; std::copy(it, end, std::ostream_iterator<int>(std::cout)); std::cout << std::endl; return 0; } 

You just need to replace buffer with ifstream , which reads the binary and writes the output to a text file, using ofstream instead of cout .

+2
source

Source: https://habr.com/ru/post/888037/


All Articles