Check processor type during RUN for program C on MAC

How does C program determine if it runs on a Little-Endian or Big-Endian processor during RUN (not compilation time)?

The reason this should be a "run-time" check rather than a "complie-time" is because I am building a program in MAC OSX Universal Binary format using my MAC address with an Intel-CPU. It is expected that this program will work both on Intel processors and on Power-PC. those. through the universal binary format on the MAC, I want to create a program using Intel-CPU and run it under the PPC processor.

The logic in my program that needs to check the CPU is the function of changing the order of the host and network for 64-bit integers. Right now I have it blindly changing byte orders that work well on Intel-CPU, but break on PPC. Here's the C function:

unsigned long long
hton64b (const unsigned long long h64bits) {
   // Low-order 32 bits in front, followed by high-order 32 bits.
   return (
       (
        (unsigned long long)
        ( htonl((unsigned long) (h64bits & 0xFFFFFFFF)) )
       ) << 32
      )
      |
      (
       htonl((unsigned long) (((h64bits) >> 32) & 0xFFFFFFFF))
      );
}; // hton64b()

Best way to do it in a cross-platform way?

thanks

+3
source share
4 answers
  • There will be preprocessor macros available for testing large / small endian. eg.
   #ifdef LITTLE_ENDIAN
   do it little endian way
   #else 
   do it big endian way
   #endif.

This is compilation time, but the source of fat binaries are compiled separately for each architecture, this is not a problem.

  • , macosx betoh64() sys/endian.h - - , .
  • - , endian - .

    uint64_t unpack64(uint8_t *src)
    {
       uint64_t val;
    
       val  = (uint64_t)src[0] << 56;
       val |= (uint64_t)src[1] << 48;
       val |= (uint64_t)src[2] << 40;
       val |= (uint64_t)src[3] << 32;
       val |= (uint64_t)src[4] << 24;
       val |= (uint64_t)src[5] << 16;
       val |= (uint64_t)src[6] <<  8;
       val |= (uint64_t)src[7]      ;
    
       return val;
    }
    
+1

; hton * , . , , , , .

, , hton *, , , . , , , .

, , , .

+2

, mac , ? , , configure/make ... gcc- (, LITTLE_ENDIAN)

0

Source: https://habr.com/ru/post/1724520/