开发者

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 开发者_StackOverflowand Float.floatToIntBits?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜