Rajesh
Rajesh

Reputation:

uint8_t to float in objective C

How to convert 4 uint8_t array elements into float in Objective c?

I tried the shift operator and it doesn't seem to work:(

Upvotes: 0

Views: 3530

Answers (2)

Dewayne Christensen
Dewayne Christensen

Reputation: 2094

The same way you do it in plain old C, cast it:

float f = (float) intArray[x];

Full example:

#import <Foundation/Foundation.h>

int
main(int argc, char** argv)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    uint8_t ints[4] = { 1, 2, 3, 4 };
    float floats[4];
    floats[0] = (float) ints[0];
    floats[1] = (float) ints[1];
    floats[2] = (float) ints[2];
    floats[3] = (float) ints[3];

    NSLog(@"floats[0]: %f", floats[0]);
    NSLog(@"floats[1]: %f", floats[1]);
    NSLog(@"floats[2]: %f", floats[2]);
    NSLog(@"floats[3]: %f", floats[3]);

    [pool release];
}

Upvotes: 0

Richard Pennington
Richard Pennington

Reputation: 19965

Are you thinking of something as undefined as this?:

union U8f {
    uint8_t byte[4];
    float f;
};

...
union U8f u8f;
u8f.byte[0] = ...
u8f.byte[1] = ...
...

float f = u8f.f;

Remember, byte order matters. I'll stand back and wait for the well deserved criticism. ;-)

Upvotes: 4

Related Questions