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?
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.