COMS 3157 Advanced Programming

Index of 2024-1/code/14

Parent directory
endian-demo.c

endian-demo.c

#include <stdio.h>
#include <assert.h>
#include <arpa/inet.h>

int main(int argc, char **argv)
{
    if (argc == 1) { // Write an int as host byte order and network byte order

        const char *HOST_FILE = "endian-demo.host";
        const char *NET_FILE  = "endian-demo.net";
        unsigned int num_host;
        unsigned int num_net;

        printf("Enter a hexadecimal integer: ");
        scanf("%x", &num_host);
        printf("The hex number 0x%.8x is %d in decimal\n", num_host, num_host);

        FILE *f = fopen(HOST_FILE, "wb");
        assert(f);
        fwrite(&num_host, sizeof(num_host), 1, f);
        printf("Wrote num_host to %s\n", HOST_FILE);
        fclose(f);

        num_net = htonl(num_host);

        f = fopen(NET_FILE, "wb");
        assert(f);
        fwrite(&num_net, sizeof(num_net), 1, f);
        printf("Wrote num_net to %s\n", NET_FILE);
        fclose(f);

        printf("You can \"xxd <filename>\" to see the content of a file\n");

    } else { // Read an int from a file

        FILE *f = fopen(argv[1], "rb");
        assert(f);
        unsigned int n;
        fread(&n, sizeof(n), 1, f);
        printf("Read int from %s: 0x%.8x (or %d)\n", argv[1], n, n);

        printf("Logically: (Most Significant Byte) "
                "%.2x %.2x %.2x %.2x (Least Significant Byte)\n", 
                (n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff);

        char *p = (char *)&n;
        printf("Physically in memory: (First Byte) "
                "%.2x %.2x %.2x %.2x (Last Byte)\n",
                p[0], p[1], p[2], p[3]);
    }
}