Click to See Complete Forum and Search --> : cast


HP_
July 20th, 2008, 12:55 AM
have a buffer of type integer (4 bytes) with 1000 elements. what is quickest method to typecast each element to short (2 bytes) before writing it a binary opened file?.

S_M_A
July 20th, 2008, 06:17 AM
A non-portable (doesn't work for big-endian machines) could be:int32 arr[1000];
FILE* pF;
for( int i = 0; i < 1000; ++i ) fwrite( &arr[i], 2, 1, pF );An endian independent version requires a temporary buffer.

Edit: I assume that you're sure that the elements only contains "16-bit values"?

Neolisk
July 20th, 2008, 08:01 AM
Why not just cast explicitly with "(short)" ?