Binary to Hex Converter


This source code below converts a text file with binaries into a text file with hexadecimals. Imagine we have a file of binaries called “hello.bin”, we are going to convert it into hexadecimals and write it into a file called “hello.com”.

hello.bin

10110100 00001001
10111010 00001001 00000001
11001101 00100001
11001101 00100000
01101000 01100101 01101100 01101100 01101111 00100100

Concept (in terms of ASM)

mov ah,09
mov dx,0109
int 21
int 20
db "hello$"

hello.com

B4 09 BA 09 01 CD 21 CD 20 68 65 6C 6C 6F 24

where you can see how the binaries, hexadecimals and ASM are linked.

10110100 = B4 = mov ah
00001001 = 09 = 09

What “hello.com” does when ran is it prints the word “hello” and exits. Generally this code is a converter but it has given me a further insight of what assembly would look like and how the machine language works now. The source code is as below and it is done in C language (but you would need to write the filename as .cpp instead of .c since the program was not programmed according the C proper structure whereby it should be defining variables before statements).

Source code

#include <stdio.h>
#include <stdlib.h>

void help(char* fname) {
    printf(
        "Code programs in binary - by Jakash3\n"
        "Usage: %s outfile infile"
        "Notes:\n"
        "   infile = Text file containing ascii 1's and 0's.\n"
        "            8 bits per byte, all other characters\n"
      "            and whitespace ignored.\n"
        "   outfile = Name of program to create and write to.\n",
        fname
    );
    exit(1);
}

int main(int argc, char** argv) {
    if (argc!=3) help(argv[0]);
    FILE *dst, *src;
    dst = fopen(argv[1],"wb");
    if (!dst) { printf("Could not create or truncate %s\nQuitting...",argv[1]); return 1;}
    src = fopen(argv[2],"r");
    if (!src) { printf("Could not open %s\nQuitting...",argv[2]); return 1;}
    char c, byte=0;
    int i=0, count=0;
    while (!feof(src)) {
        if (i==8) { fwrite(&byte,1,1,dst); byte=0; i=0; count++; }
        fread(&c,1,1,src);
        switch (c) {
            case '1':
                byte |= ((c=='1') << (7-i));
            case '0':
                i++;
        }
    }
    fclose(src);
    if (!fclose(dst))
        printf("Wrote %d bytes to %s\n",count,argv[1]);
    return 0;
}

Download binary (.exe).

This code was written by jakash3 from Leetcoders.org
* Original link here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: