Question

I am porting some Java code to Objective C and know enough bitwise to get a headache. Can someone point me to the objC equivalents to Double.doubleToLongBits and Float.floatToIntBits?

Was it helpful?

Solution

There's no safe way to assign the bits of a double to a long in Objective C. In Java, long and double are both 64bits. In some cases for Objective C, long is 32bit and double is 64bit.

You should use long long instead.

int intValue = *((int*)(&floatValue));
long long llValue = *((long long*)(&doubleValue));

OTHER TIPS

As jojoba noted, long isn't guaranteed to be 64 bits wide (though he's wrong to say that it's 32 bits -- long is 64 bits wide in Objective-C on 64-bit platforms). That said, I would use an actual fixed width type instead of long long.

#include <stdint.h>

uint64_t doubleToBits(double x) {
    const union { double f; uint64_t i; } xUnion = { .f = x };
    return xUnion.i;
}

uint32_t floatToBits(float x) {
    const union { float f; uint32_t i; } xUnion = { .f = x };
    return xUnion.i;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top