+2  A: 

You're running this on a little-endian platform.

On a little-endian platform, a 32-bit int is stored in memory with the least significant byte in the lowest memory address. So bits 0-7 are stored at address P, bits 8-15 in address P + 1, bits 16-23 in address P + 2 and bits 24-31 in address P + 3.

In your example: bits 0-7 = 't', bits 8-15 = 's', bits 16-23 = 'e', bits 24-31 = 't'

So that's the order that the bytes are written to memory: "tset"

If you address the memory then as separate bytes (unsigned chars), you'll read them in the order they are written to memory.

Jesper
+8  A: 

This is because your CPU is little-endian. In memory, the array is stored as:

      +----+----+----+----+
array | 74 | 65 | 73 | 74 |
      +----+----+----+----+

This is represented with increasing byte addresses to the right. However, the integer is stored in memory with the least significant bytes at the left:

    +----+----+----+----+
out | 74 | 73 | 65 | 74 |
    +----+----+----+----+

This happens to represent the integer 0x74657374. Using memcpy() to copy that into buff reverses the bytes from your original array.

Greg Hewgill
Bah. Smacks self in head. Thanks for the explanation.
bizack
A: 

On a little-endian platform the output should be tset. The original sequence was test from lower addresses to higher addresses. Then you put it into an unsigned int with first 't' going into the most significant byte and the last 't' going into the least significant byte. On a little-endian machine the least significant byte is stored at lower address. This is how it will be copied to the final buf. This is how it is going to be output: from the last 't' to the first 't', i.e. tset.

On a big-endian machine you would not observe the reversal.

AndreyT
A: 

how about adding a '\0' to your buff?

Anders K.
A: 

You have written a test for platform byte order, and it has concluded: little endian.

DigitalRoss