Skip to content

Instantly share code, notes, and snippets.

@babhishek21
Last active January 29, 2017 06:44
Show Gist options
  • Save babhishek21/b0c80d104de383f1a21e12e2981f075e to your computer and use it in GitHub Desktop.
Save babhishek21/b0c80d104de383f1a21e12e2981f075e to your computer and use it in GitHub Desktop.
Simulate reverse process of the xxd command
/**
* Program: Simulate reverse xxd (to convert hex dump to binary RAW file)
* Author: Abhishek Bhattacharya
*/
#include <bits/stdc++.h>
using namespace std;
unsigned int make_4_bit_binary(char &ch) {
unsigned int hexval;
if(ch >= '0' && ch <= '9')
hexval = ch - '0';
else {
hexval = ch - 'a' + 10;
}
return hexval & 0xff;
}
int main(int argc, char *argv[]) {
if(argc >= 2 && string(argv[1]) == "--help") {
cout << "HELP:" << endl
<< "\n<executable_file_name> [--help] hexdump_file_name binary_destination_file_name" << endl
<< "\nNOTE: The hexdump_file should be of a specific format. The right format is achieved using:" << endl
<< "\n$> xxd -p source_binary_file_name > hexdump_file_name\n" << endl;
} else if(argc < 3) {
cout << "ERROR: Too few arguments passed. Are you sure you passed the name of the FILEs?" << endl;
return 0;
}
string buff;
ifstream fin(argv[1]);
ofstream fout(argv[2], ios::out|ios::binary);
unsigned int out1, out2;
char outc;
if(fin.is_open() && fout.is_open()) {
while(getline(fin, buff)) {
for(size_t i = 0; i<buff.size(); i+=2) {
// accumulate 8 bits of data
// check if full 8 bits of data not available
if(i == buff.size()-1)
out2 = 0x00;
else
out2 = make_4_bit_binary(buff[i+1]);
out1 = make_4_bit_binary(buff[i]);
outc = (out1 << 4) + (out2 & 0x0f);
// debug
// cout << buff[i] << ((i == buff.size()-1) ? '0' : buff[i+1]) << " => " << out1 << " " << out2 << " -> " << outc << endl;
// write binary 8-bit block
fout.write(&outc, sizeof(outc));
}
}
// fin.close();
// fout.close();
} else
cout << "ERROR: FILE " << argv[1] << " and/or " << argv[2] << " could not be opened. \
Check the files and try again." << endl;
return 0;
}

Reverse xxd

A simple experiment to simulate the reverse effect of the xxd command. Converts a raw hexdump made with xxd back to a RAW binary file.

Usage

Compile as C++98 or above.

<executable_file_name> [--help] hexdump_file_name binary_destination_file_name

Example usage:

xxd -p sample.jpg test.hex
reverse_xxd test.hex sample_copy.jpg

License

Distributed under the MIT License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment