fuzzygoat
fuzzygoat

Reputation: 26223

Converting NSData to float?

Initially I thought the code presented below was working, the "inBuffer" seems to be correctly getting 4-bytes of data, also the variable MDD_times is correct.

NSData *inBuffer;
float MDD_times;

// FLOAT_002
inBuffer = [inFile readDataOfLength:sizeof(float)];
[inBuffer getBytes: &MDD_times length:sizeof(float)];
NSLog(@"Time: %f", MDD_times);

OK let me expand on this little (code above updated), this is what I am getting:

inBuffer = <3d2aaaab>
MDD_times = -1.209095e-12 (this will be 0.0416667 bigEndian)
NSLog(@"Time: %f", MDD_times) = Time: -0.000000

Its probably NSLog that can't accommodate the float value, I flipped the bytes in the float to bigEndian and the expected value "0.0416667" displays just fine. AT least I know the NSData > float bit is working as intended.

gary

Upvotes: 0

Views: 2755

Answers (2)

nall
nall

Reputation: 16139

Here's some code I have to do this at a given offset in a buffer. This should work regardless of host endianness when the file is in big endian format.

union intToFloat
{
    uint32_t i;
    float fp;
};

+(float)floatAtOffset:(NSUInteger)offset
               inData:(NSData*)data
{
    assert([data length] >= offset + sizeof(float));
    union intToFloat convert;

    const uint32_t* bytes = [data bytes] + offset;
    convert.i = CFSwapInt32BigToHost(*bytes);

    const float value = convert.fp;

    return value;
}

Upvotes: 6

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

If you’re sure that the inFile returns data that was encoded with the same type of float and the same endianness, your code should work as expected.

Upvotes: 2

Related Questions