Alex Rivera | Logout

Imitate/emulate a big-endian behavior in C?

Asked 2010-07-26T18:41:00.973
26

I was wondering if it's possible to emulate a big-endian behavior, for testing purpose?

via either windows or linux , mingw or gcc. Here's a sample of code which I would like the emulation to return big endian:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <limits.h>
#if CHAR_BIT != 8
#error "Unsupported char size for detecting endianness"
#endif

int main (void)
{
  short int word = 0x0001;
  char *byte = (char *) &word;
  if (byte[0]) printf("little endian");
  else printf("big endian");
  return 0;
}
Edit
Report

1 Answer

0

Why would you want to detect the endianness of your platform at run-time? When you go to compile, the endian mode is known. Your code will do what you expect it to... assuming that a short int is 2 bytes on the target platform. To avoid this hangup, you'd be better off looking at the last byte. (byte[sizeof(short int) - 1])

answered 2010-07-26T18:48:21.963

Your Answer