0

I know the way of non meta programing to decide a PC is little endian or not.

eg:

#include <iostream>
#include <stdint.h>

union A { 
    uint16_t v;
    char c[2];
};  

int main(void) {
    A a;
    a.v = 0x0102;
    std::cout << (a.c[0] == 0x01 ? "big endian" : "little endian") << std::endl;

    return 0;
}

But, it's expensive in run time, isn't it?

So, is there a way to decide a PC is little endian or not by meta programing?

Thanks!

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
superK
  • 3,932
  • 6
  • 30
  • 54
  • Depends on your specific compiler -- look here for some hairy details: http://gcc.gnu.org/ml/gcc-help/2007-07/msg00342.html – michel-slm Sep 27 '12 at 03:13
  • Already been asked http://stackoverflow.com/questions/8571089/how-can-i-find-endian-ness-of-my-pc-programmatically-using-c – AnthonyFG Sep 27 '12 at 03:15
  • @AnthonyFG No, that issue is not solved by meta programing. – superK Sep 27 '12 at 04:15
  • 4
    What do you mean by "expensive"? Time? Complexity? Memory? Have you measured? The most "expensive" I see in your example code is the output, everything else is small, fast and trivial. – Some programmer dude Sep 27 '12 at 07:15
  • See http://stackoverflow.com/questions/2100331/c-macro-definition-to-determine-big-endian-or-little-endian-machine @ Norman Ramsey – Mikhail Sep 27 '12 at 07:23
  • @JoachimPileborg Sorry, I described not detailed enough. "expensive" means time and memory. If we can decide our endian at compile time, why we call a function at run time to decide it? It will use CPU cycle. and memory. So I think get the answer at compile time is better than run time. – superK Sep 27 '12 at 08:01
  • On a modern PC-class CPU the actual check will be sub-millisecond, and will hardly exceed 32 bytes (including data _and_ instructions), and it needs only be done once. Unless your program is **very** small, this will likely be less than 0.01 percent of both CPU time and memory requirements. You have to be programming for **extremely** small systems for this to be considered a problem, and in those cases you already know the byte-order and will adjust for it beforehand. – Some programmer dude Sep 27 '12 at 08:10
  • 1
    Also, if you do it during compilation-time, you can't use the program when cross-compiling to a target of different byte-order than the host. – Some programmer dude Sep 27 '12 at 08:11

1 Answers1

0

There's nothing in the language that requires a target computer to be exclusively big-endian or exclusively little-endian. Indeed, some architectures allow endianness selection by the software at run time. Some even allow per-page endianness selection.

A template metaprogram cannot possibly know anything about this stuff.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243