Page 1 of 1

Making C read blocks of arrays as little endian

Posted: Sat Mar 21, 2009 10:04 am
by Troy Martin
Is there any way to have C read 16-bit words in an array of chars as little endian format on any architecture? I'm writing an emulator for a little-endian architecture I designed and I want it to act little-endian on any architecture it's compiled on.

example char array loaded from a file:

Code: Select all

char memory[1024] = {
0x10,0x28,0xF0,0xF0 };
The two bytes in the middle is a little-endian word. Therefore, when loaded out of memory and into a register (or the PC), it's the word 0xF028.

Thanks,
Troy

Re: Making C read blocks of arrays as little endian

Posted: Sat Mar 21, 2009 11:23 am
by JamesM
Cast the relevant area to a 16-bit integer and dereference. Thus:

Code: Select all

uint16_t intvalue = * (uint16_t)&memory[1];

Re: Making C read blocks of arrays as little endian

Posted: Sat Mar 21, 2009 12:18 pm
by bewing
JamesM wrote:Cast the relevant area to a 16-bit integer and dereference.
I'm afraid that won't work on quite a few occasions. First, that memory fetch would be misaligned in the example given, which may cause an alignment fault on x86 machines -- and may crash bigendian machines. Second, it won't give you the proper byte order on bigendian machines.

@Troy: since your example is misaligned, there is only one easy way to solve the problem. You must FORCE the byteorder of the result.
It is fortunate that your example is already in the form of a char array.

Code: Select all

	p = ptr to 1st byte of "16 bit word"
	little_endian_word = *p | (p[1] << 8);

Re: Making C read blocks of arrays as little endian

Posted: Sat Mar 21, 2009 12:46 pm
by ru2aqare
There are lots of macros that do exactly this. For example, htons and htonl come to mind, but I'm sure there are others.

Re: Making C read blocks of arrays as little endian

Posted: Sat Mar 21, 2009 1:58 pm
by Troy Martin
@bewing: Thanks a ton, works great!

Re: Making C read blocks of arrays as little endian

Posted: Wed Mar 25, 2009 8:18 am
by JamesM
I crafted a reply to bewing, then looked over the problem description again and did notice that it explicitly mentioned endianness. So my reply is indeed unsafe - apologies.