[Linux] Convert binary file to C struct header

Questions about programming languages and debugging
Post Reply
User avatar
ayu
Staff
Staff
Posts: 8109
Joined: 27 Aug 2005, 16:00
18
Contact:

[Linux] Convert binary file to C struct header

Post by ayu »

A good bash script to use in Linux to convert a binary file to a C struct header file.

Original source:

Code: Select all

http://www.linuxjournal.com/content/convert-file-c-data-structure
My slightly modified version:

Code: Select all

#!/bin/bash

if [[ $# -ne 1 ]]; then
    echo "Usage: $0 FILENAME"
    exit 1
fi
file=$1

if [[ ! -f "$file" ]]; then
    echo "File not found: $file"
    exit 1
fi

cname=$file
cname=${cname//-/_}
cname=${cname//./_}

echo "static unsigned char $cname[] = {" >> header.h
hexdump -v -e '" " 16/1 "  0x%02x, " "\n"' $file | sed -e '$s/0x  ,//g' >> header.h
echo "};" >> header.h
"The best place to hide a tree, is in a forest"

User avatar
ayu
Staff
Staff
Posts: 8109
Joined: 27 Aug 2005, 16:00
18
Contact:

Re: [Linux] Convert binary file to C struct header

Post by ayu »

Here's some code for writing the struct back to a binary file again.

In my example here I take the "header.h" file that the above code generates, and writes it to a file called "file.exe".
The file used to make a struct and then write it back to a binary file here, is netcat, or "nc.exe"

Code: Select all

#include "header.h"
#include <stdio.h>

int main()
{

    FILE* fd = 0;

    fd = fopen( "file.exe", "wb");
    fwrite(nc_exe, sizeof(nc_exe), 1, fd);
    fclose(fd);

    return 0;
}
"The best place to hide a tree, is in a forest"

Post Reply