1

Assuming the following C code runs on a 32 bit platform (so sizeof(int) = 4), is the following code portable between big endian and little endian? When I ask "is it portable" I mean is the app going to print:

a) on a little endian platform

Address is 0xAABBCCDD
MSB is AA
LSB is DD
little endian

b) on a big endian platform

Address is 0xAABBCCDD
MSB is AA
LSB is DD
big endian

?

#include <stdio.h>

typedef unsigned char uint8;
typedef unsigned int uint32;

#define is_bigendian() ( (*(uint8*)&var) == 0 )

int main()
{
    uint32 var = 1;
    uint8 msb;
    uint8 lsb;
    printf("Address is %x\n", (uint32)&var);
    msb = (((uint32)&var) & 0xFF000000) >> 24;
    lsb = (((uint32)&var) & 0x000000FF) >> 0;
    printf("MSB is %x\n", msb);
    printf("LSB is %x\n", lsb);
    if (is_bigendian())
    {
        printf("big endian\n");
    }
    else
    {
        printf("little endian\n");
    }
    return 0;
}
Sterpu Mihai
  • 486
  • 1
  • 4
  • 15
  • endianness effects you only when you are operating between data types with different size. – kiran Biradar Jun 21 '20 at 06:26
  • 1. Do not define your own integral types, use the standard. ones. 2. `is_bigendian()` makes no sense, `var` is always zero, all bytes of it. 3. You do not need to know about endianness. Bit operations don't care about it. – n. m. could be an AI Jun 21 '20 at 06:30
  • The answer to the title is, "Yes". – user3386109 Jun 21 '20 at 06:42
  • @n.'pronouns'm. sorry, edit error, of course var needs to be different than 0 in order for the macro to work; my question is whether or not lsb and msb vars will have the same values on big endian and little endian architectures – Sterpu Mihai Jun 21 '20 at 07:33
  • yes they will be the same – n. m. could be an AI Jun 21 '20 at 07:51
  • @kiranBiradar No, that's not all. Endianness effects you, too, if you mix data types of the same size on systems with different endianness. Literals and values in registers are not effected, just values stored in memory cells of a smaller size than the data size. – the busybee Jun 21 '20 at 08:40
  • user3386109 or n.'pronouns'm: Please make this an answer, so that SterpuMihai can mark it. – the busybee Jun 21 '20 at 08:41
  • 1
    The code makes no sense. If an address is, when interpreted as an integer, 0xAABBCCDD, then its most significant byte (as a 32-byte integer) is 0xAA and its least significant byte is 0xDD, and this has nothing to do with endianness. Shifting and masking the address has nothing to do with endianness. If you are trying to investigate the endianness with which values are stored in memory, then you need to examine the bytes in memory. – Eric Postpischil Jun 21 '20 at 10:38
  • @EricPostpischil actually you just answered to my question :) this is exactly what I was curious, if that code prints the same lsb and msb values (provided the address is the same) on big endian and little endian – Sterpu Mihai Jun 21 '20 at 11:46

0 Answers0