445,797 Members | 1,794 Online
Need help? Post your question and get tips & solutions from a community of 445,797 IT Pros & Developers. It's quick & easy.

# Memory Alignment Problem

 P: n/a Hi, Good day! Anyone knows how to extract shorts, long, chars from a char array considering the memory alignment? It's like this, there's a char buffer, which is cast into a struct, then cast back to a char pointer. The first two chars should be a short; when displayed as char the number (value 0x8600, equal to 134) is correct but when a short pointer is pointed to this char and the short is displayed, it becomes a negative number (-31232). TIA, Roy Mar 16 '07 #1
3 Replies

 P: n/a iduniq wrote: Hi, Good day! Anyone knows how to extract shorts, long, chars from a char array considering the memory alignment? It's like this, there's a char buffer, which is cast into a struct, then cast back to a char pointer. The first two chars should be a short; when displayed as char the number (value 0x8600, equal to 134) is correct but when a short pointer is pointed to this char and the short is displayed, it becomes a negative number (-31232). The bit pattern 0x8600 is -31232 when cast to a (16 bit) short. Are you muddling up signed and unsigned types? -- Ian Collins. Mar 16 '07 #2

 P: n/a Ian Collins wrote: > iduniq wrote: Hi, Good day! Anyone knows how to extract shorts, long, chars from a char array considering the memory alignment? It's like this, there's a char buffer, which is cast into a struct, then cast back to a char pointer. The first two chars should be a short; when displayed as char the number (value 0x8600, equal to 134) is correct but when a short pointer is pointed to this char and the short is displayed, it becomes a negative number (-31232). The bit pattern 0x8600 is -31232 when cast to a (16 bit) short. Are you muddling up signed and unsigned types? I think he's mixing up endianness. If you have: char foo[] = { 0x86, 0x00 }; and read *(short *)foo on a little-endian, 16-bit-short, properly- aligned system, you will probably (though it's probably UB according to the standard) read 134 (0x0086). However, on a big-endian, everything-else-the-same-as-before system, you will probably read -31232 (0x8600). -- +-------------------------+--------------------+-----------------------+ | Kenneth J. Brody | www.hvcomputer.com | #include | | kenbrody/at\spamcop.net | www.fptech.com | Mar 16 '07 #3

 P: n/a Hi guys, I'm very sorry I only realise my fault after I sent SOS. Ian is correct, there was a prior ntosh before this code. Thanks, Roy On Mar 16, 9:49 pm, Kenneth Brody Mar 20 '07 #4

### This discussion thread is closed

Replies have been disabled for this discussion.