简体   繁体   English

Obj C等效于Double.doubleToLongBits

[英]Obj C Equivalent to Double.doubleToLongBits

I am porting some Java code to Objective C and know enough bitwise to get a headache. 我正在将一些Java代码移植到Objective C,并且了解足够多的内容以至于头疼。 Can someone point me to the objC equivalents to Double.doubleToLongBits and Float.floatToIntBits? 有人可以指出我指向Double.doubleToLongBits和Float.floatToIntBits的objC等效项吗?

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). 正如jojoba指出的那样,不能保证long宽度为64位(尽管他错了说它是32位的-在64位平台上的Objective-C中long为64位)。 That said, I would use an actual fixed width type instead of long long . 也就是说,我将使用实际的固定宽度类型而不是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. 在Objective C中,没有安全的方法将double的位分配给long 。在Java中, longdouble都是64位。 In some cases for Objective C, long is 32bit and double is 64bit. 在某些情况下,对于目标C, long是32位,而double是64位。

You should use long long instead. 您应该使用long long代替。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM