Discussion in 'C++' started by kelvSYC, Jun 3, 2005.

  1. kelvSYC

    kelvSYC Guest

    Are there any endianness concerns in C++, or does the compiler take
    care of those details? I ask because I'm not sure if code such as the
    following have consistent behavior on all platforms.

    typedef unsigned int u32; // sizeof(int) == 4
    typedef unsigned char u8;

    u8 array[4] = { 0x01, 0x23, 0x45, 0x67 };
    *((u32*) array) = 0x89ABCDEF;

    Will array contain { 0x89, 0xAB, 0xCD, 0xEF } or { 0xEF, 0xCD, 0xAB,
    0x89 }, or even something else?
    kelvSYC, Jun 3, 2005
    1. Advertisements

  2. kelvSYC

    John Carson Guest

    Sure, as long as you don't do silly things like cast between an array of
    chars and an int.
    Depends on endianness.
    John Carson, Jun 3, 2005
    1. Advertisements

  3. * kelvSYC:
    Except for seralization to/from byte stream it's easy to code such
    that endianness doesn't matter.

    AFAIK the language offers no support for endian-specific code.

    std::numeric_limits<T> can tell you whether an integer type is an integer
    type, whether it's got modulo arithemetic, and whether it's signed or
    not, but it doesn't tell you anything about endianness.

    It doesn't.

    As a practical matter the result depends on the endianness, as you've

    As a formal matter the camouflaged reinterpret_cast in there makes it
    all either UB or implementation defined, I'm not sure which.

    Anyway, all you have to do to avoid that unpleasantness is to NOT USE
    REINTERPRETATION CASTS, and that includes not using C-style casts. ;-)
    Alf P. Steinbach, Jun 3, 2005
  4. As others have pointed out, only if you write endian-dependent code.

    The only reason I can think of to write endian-dependent code is as another
    poster pointed out, if you're trying to serialize data. If you do this, you
    need to have a consistent policy about endianness and byte representation.
    No. You need some sort of preliminary configuration to detect endianness.
    No. You can use similar code to test endianness. BTW, you also need to be
    careful with different size ints.

    Donovan Rebbechi, Jun 3, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.