Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to view a binary in ones and zeros?

Tags:

c

By that I mean is it possible to write a program in C, compile it and then see what it looks like in ones and zeros?

like image 412
Isaiah Avatar asked Dec 01 '22 07:12

Isaiah


1 Answers

You can use xxd:

xxd -b filename
C:\opt\bin> xxd -b ctags.exe | head
0000000: 01001101 01011010 10010000 00000000 00000011 00000000  MZ....
0000006: 00000000 00000000 00000100 00000000 00000000 00000000  ......
000000c: 11111111 11111111 00000000 00000000 10111000 00000000  ......
0000012: 00000000 00000000 00000000 00000000 00000000 00000000  ......
0000018: 01000000 00000000 00000000 00000000 00000000 00000000  @.....
000001e: 00000000 00000000 00000000 00000000 00000000 00000000  ......
0000024: 00000000 00000000 00000000 00000000 00000000 00000000  ......
000002a: 00000000 00000000 00000000 00000000 00000000 00000000  ......
0000030: 00000000 00000000 00000000 00000000 00000000 00000000  ......
0000036: 00000000 00000000 00000000 00000000 00000000 00000000  ......

Just to make this a little more programming related:

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

const char *lookup[] = {
   /*  0       1       2       3       4       5       6       7 */
    "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
   /*  8       9       A       B       C       D       E       F */
    "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111",
};

int main(int argc, char *argv[]) {
    FILE *fin;
    int c;
    size_t bytes_read = 0;

    if ( argc != 2 ) {
        fputs("No filename provided", stderr);
        exit(EXIT_FAILURE);
    }

    fin = fopen(argv[1], "rb");
    if ( !fin ) {
        fprintf(stderr, "Cannot open %s\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    while ( EOF != (c = fgetc(fin)) ) {
        printf("%s", lookup[ (c & 0xf0) >> 4 ]);
        printf("%s", lookup[ (c & 0x0f) ]);

        bytes_read += 1;
        if ( bytes_read % 9 == 0 ) {
            puts("");
        }
    }

    fclose(fin);

    return EXIT_SUCCESS;
}

Output:

C:\Temp> binary.exe c:\opt\bin\ctags.exe | head
010011010101101010010000000000000000001100000000000000000000000000000100
000000000000000000000000111111111111111100000000000000001011100000000000
000000000000000000000000000000000000000000000000010000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000111000000000000000000000
000000000000111000011111101110100000111000000000101101000000100111001101
001000011011100000000001010011001100110100100001010101000110100001101001
011100110010000001110000011100100110111101100111011100100110000101101101
like image 165
Sinan Ünür Avatar answered Dec 26 '22 09:12

Sinan Ünür