summaryrefslogtreecommitdiff
path: root/archived/less_old_sim8086/code/print_binary.c
blob: 1382cae556851fbe00764222d8b47ee717eb8533 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <signal.h>

#define Assert(Expr) \
    if (!(Expr)) \
    { \
        raise(SIGTRAP); \
    }


int
main(int ArgC, char *Args[])
{
    if (ArgC < 2)
    {
        fprintf(stderr, "Missing argument.\n");
        fprintf(stderr, "Usage: %s <filename>\n", Args[0]);
    }
    else
    {    
        struct stat StatBuffer = {0};
        char *Filename = 0;
        int FD = -1;
        int Err = -1;
        size_t Filesize = 0;
        char *Buffer = 0;
        
        Filename = Args[1];
        FD = open(Filename, O_RDONLY);
        Assert(FD != -1);
        Err = stat(Filename, &StatBuffer);
        Assert(Err != -1);
        Filesize = StatBuffer.st_size;

        if (Filesize)
        {
            Buffer = mmap(0, Filesize, PROT_READ, MAP_SHARED, FD, 0);
            Assert(Buffer);

            for (size_t At = 0; At < Filesize; At++)
            {
                unsigned char Byte = Buffer[At];
                int Count = 8;
                while (Count--)
                {
                    printf("%d", Byte >> 7);
                    Byte <<= 1;
                }
                printf(" ");
            }
            printf("\n");
        }
        else
        {
            fprintf(stderr, "Empty file.\n");
        }
    }

    return 0;
}