문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top