WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C · Advanced · question 60 of 100

Explain the difference between big-endian and little-endian memory representations, and how to handle them in C programs.?

📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

In computer memory, multi-byte data types such as integers, floats, and doubles are stored as a series of bytes. The order in which these bytes are arranged in memory is called the endianness of the system. There are two commonly used byte orders: big-endian and little-endian.

In big-endian, the most significant byte of a multi-byte data type is stored at the lowest memory address, and the least significant byte is stored at the highest memory address. Conversely, in little-endian, the least significant byte is stored at the lowest memory address, and the most significant byte is stored at the highest memory address.

For example, let’s consider the 32-bit integer value 0x12345678. In big-endian, the bytes would be arranged as:

    0x12 0x34 0x56 0x78

while in little-endian, the bytes would be arranged as:

    0x78 0x56 0x34 0x12

To handle endianness in C programs, we can use byte-level manipulation techniques such as bitwise shifting and masking. For example, to convert a little-endian byte array to a 32-bit integer on a big-endian system, we could use the following code:

    #include <stdint.h>
    
    uint32_t little_endian_to_int(unsigned char* bytes) {
        uint32_t result = 0;
        for (int i = 0; i < 4; i++) {
            result |= (bytes[i] << (8 * i));
        }
        return result;
    }

In this function, we iterate through each byte of the input array and shift it left by the appropriate number of bits based on its position in the array. We then combine the shifted bytes using bitwise OR to obtain the final 32-bit integer value.

Similarly, to convert a 32-bit integer to a big-endian byte array on a little-endian system, we could use the following code:

    void int_to_big_endian(uint32_t value, unsigned char* bytes) {
        for (int i = 0; i < 4; i++) {
            bytes[i] = (value >> (8 * (3 - i))) & 0xFF;
        }
    }

In this function, we iterate through each byte of the output array and shift the input value right by the appropriate number of bits based on the byte’s position in the array. We then use bitwise AND with 0xFF to mask off any extraneous bits and obtain the final byte value.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C interview — then scores it.
📞 Practice C — free 15 min
📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

All 100 C questions · All topics