Apple Developer Connection
Member Login Log In | Not a Member? Contact ADC

< Previous PageNext Page > Hide TOC

Byte Order

Microprocessor architectures commonly use two different byte-ordering methods (little-endian and big-endian) to store the individual bytes of multibyte data formats in memory. This difference becomes critically important if you try to read data from files that were created on a computer that uses a different byte ordering than yours. You also need to consider byte ordering when you send and receive data through a network connection and handle networking data. The difference in byte ordering can produce incorrect results if you do not account for this difference. For example, the order of bytes in memory of a scalar type is architecture-dependent, as shown in Listing 2-1.

Listing 2-1  Code that illustrates byte-ordering differences

unsigned char charVal;
unsigned long value = 0x12345678;
unsigned long *ptr = &value;
charVal = *(unsigned char*)ptr;

On a processor that uses little-endian addressing the variable charVal takes on the value 0x78. On a processor that uses big-endian addressing the variable charVal takes on the value 0x12. To make this code architecture-independent, change the last line in Listing 2-1 to the following:

charVal = (unsigned char)*ptr;

For a detailed discussion of byte ordering and strategies that you can use to account for byte-ordering differences, see “Swapping Bytes.”



< Previous PageNext Page > Hide TOC


Last updated: 2007-02-26




Did this document help you?
Yes: Tell us what works for you.

It’s good, but: Report typos, inaccuracies, and so forth.

It wasn’t helpful: Tell us what would have helped.
Get information on Apple products.
Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Copyright © 2007 Apple Inc.
All rights reserved. | Terms of use | Privacy Notice