Jim Geldermann
Jim Geldermann

Reputation: 183

Obj C Equivalent to Double.doubleToLongBits

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?

Upvotes: 0

Views: 765

Answers (2)

tidwall
tidwall

Reputation: 6949

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));

Upvotes: 3

Stephen Canon
Stephen Canon

Reputation: 106247

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;
}

Upvotes: 5

Related Questions