Reputation: 393
I'm reading in binary data that might possibly consist of 64 bit floats ("doubles") in the Big Endian byte-order. I read them individually into a buffer of the type Float64 using the getBytes:range: method of NSData. Now I would like to change the byte order to Little Endian. For integers, this is easily possible using the Core-Foundation function CFSwapIntXX(), with XX being the number of bits. But there are no corresponding methods for floats. What is the preferred way to do this?
I tried to "force" a 64bit double as an argument to the function CFSwapInt64() by previously memcopying it into an int64_t variable and then back again to the double value. It works correctly, but this seems rather brutal to me. Is there no method that comes with the standard framework?
Upvotes: 0
Views: 1315
Reputation: 53000
The direct support for floats uses a platform-independant format, see Byte Order Utilities. However the way you are doing it is fine, the "integer" in the swap functions isn't relevant - the functions operate on so many bytes regardless of how those bytes will be interpreted.
To avoid the ugly byte copies you can use a union
:
typedef union { Float64 floatValue; int64_t intValue; } FloatBuffer;
Fill this and byte swap it using the intValue
field and read out the value using the floatValue
field.
Upvotes: 1