Archived

This topic is now archived and is closed to further replies.

Chrono999

casting a string to a short?

Recommended Posts

I was looking at some code that looked like this: short TakeData(char* buffer) { short shortdata; long longdata; shortdata = *(short*)(buffer); longdata = *(long*)(buffer+2); return shortdata; } I don''t understand it, could somebody explain those casts to me? The buffer was pretty big, so how does this work, and what''s with the two pointers? Thanks a lot anybody who furthers my C++ knowledge!

Share this post


Link to post
Share on other sites
It casts the char pointer to a short pointer and then dereferences it to obtain the first two bytes in the buffer as a short.
Then it casts the char pointer to a long pointer to obtain the four bytes starting at index 2 of the buffer.

For example:
buffer = 0xAABBCCDDEEFF
shortdata = 0xAABB
longdata = 0xCCDDEEFF

Hope this explains it.

Jasper

Share this post


Link to post
Share on other sites
It should mentioned that this can be a very naughty thing to do if you plan to port your code to different hardware. Several of the embedded systems I''ve worked with used differenty byte ordering (big and little endian) and this causes lots of headaches when porting.

Jesse Chounard
stinkygoop@crosswinds.net

Share this post


Link to post
Share on other sites
From The Art of Assembly Language:

quote:


The Intel processor families use a memory organization known as little endian byte organization. In little endian byte organization, the L.O. byte of a multi-byte sequence appears at the lowest address in memory. For example, bits zero through even of a 32 bit value appear at the lowest address; bits eight through fifteen appear at the second address in memory; bits 16 through 23 appear in the third byte, and bits 24 through 31 appear in the fourth byte.

Another popular memory organization is big endian. In the big endian scheme, bits twenty-four through thirty-one appear in the first (lowest) address, bits sixteen through twenty-three appear in the second byte, bits eight through fifteen appear in the third byte, and bits zero through seven appear in the fourth byte. CPUs such as the Motorola 68000 family used by Apple in their Macintosh computer and many RISC chips employ the big
endian scheme.




So if you use the code above on a big endian system and it was originally intended for little endian (or vice versa) the order of the bytes is reversed.

Jasper

Share this post


Link to post
Share on other sites