How Bit Endianness Affects Bitwise Shifts and File IO in C

bitc++endianness

Let L and B be two machines. L order its bits from LSB
(Least Significant Bit) to MSB (Most Significant Bit) while B order
from MSB to LSB. Or, in other words, L uses Little Endian while
B uses Big Endian bit – not to be confused with byte – ordering.

Problem 1 SOLVED:

We are writing the following code which we want to be portable:

#include <stdio.h>

int main()
{
    unsigned char a = 1;
    a <<= 1;

    printf("a = %d\n", (int) a);

    return 0;
}

on L, it will print 2, but what happens on B? Will it shift the
1 out and print 0?.

SOLUTION: The C99 definition at 6.5.7 says it that, at least on
unsigned integer types, << and >> will multiply and divide by 2
respectively.

Problem 2:

We are writing the following code which we want to be portable:

READ program:

/* program READ */
#include <stdio.h>

int main()
{
    FILE* fp;
    unsigned char a;

    fp = fopen("data.dat", "rb");
    fread(&a, 1, 1, fp);
    fclose(fp);

    return 0;
}

and WRITE program:

/* program WRITE */
#include <stdio.h>

int main()
{
    FILE* fp;
    unsigned char a = 1;

    fp = fopen("data.dat", "wb");
    fwrite(&a, 1, 1, fp);
    fclose(fp);

    return 0;
}

what happens if we run WRITE on L, move the data file to B and
run READ there? And if we run WRITE on B and then READ on L?

Sorry if this is a FAQ. I googled for hours without luck.

Best Answer

Bit Endianness doesn't affect data stored on disks in bytes. Byte Endianness will.

Bit Endianness is something that matters for serial interfaces where a byte is sent one bit at a time, and the sender and receiver need to agree on the byte order. For example, bit order in SPI devices varies and you need to reference the data sheet before attempting to read from the device.

Here's what Wikipedia says on bit endianness:

The terms bit endianness or bit-level endianness are seldom used when talking about the representation of a stored value, as they are only meaningful for the rare computer architectures where each individual bit has a unique address. They are used however to refer to the transmission order of bits over a serial medium. Most often that order is transparently managed by the hardware and is the bit-level analogue of little-endian (low-bit first), although protocols exist which require the opposite ordering (e.g. I²C). In networking, the decision about the order of transmission of bits is made in the very bottom of the data link layer of the OSI model.

In your case, the physical hard drive interface defines the bit order, regardless of the processor that's going to read or write it.

Related Question