Converting (u)int64_t to NSNumbers
Asked Answered
U

1

9

So essentially my question is this, I am creating an NSMutableDictionary using uint64_t objects as the key.

Is there any better way to create them than doing this?

uint64_t bob=7;

NSNumber *bobsNumber;

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
bobsNumber=[NSNumber numberWithUnsignedLong:bob];
#else
bobsNumber=[NSNumber numberWithUnsignedLongLong:bob];
#endif

This would work as long as you didn't include it in a binary file/sockets/NSData object/whatever. But is there any better way of doing this? I really would like to be sure that the object is 64-bits regardless of what platform I run it on.

I guess I could just avoid the whole issue by always going unsigned long long but of course that wastes tons of heap space on 64 bit machines if I allocate these objects in any significant numbers....

Ungulate answered 19/9, 2010 at 14:15 Comment(0)
C
18

long long is 64-bit on 64-bit OS X/iOS platforms. On all OpenStep-descended platforms, numberWithUnsignedLongLong: is correct for uint64_t.

Last time I checked, which factory method you use doesn’t actually affect the representation used anyway; it’s only dependent on the value of the number (unless you use a too-small size, causing it to be truncated).

Update: these days, the correct answer is NSNumber *bobsNumber = @(bob);.

Caw answered 19/9, 2010 at 14:26 Comment(2)
The reason why it doesn't matter is that the compiler knows best about the actual bitwidths of the used types. If they do not match, one is converted into the other -- either by clipping bits or by extending with leading 0's.Brakpan
You’re misunderstanding. What I mean in the second paragraph is that [NSNumber numberWithLongLong:73] would produce the same object as [NSNumber numberWithChar:73], rather than one producing an object back by a long long and the other an object backed by a char. Now that I bother to re-check, this is not the case in 10.6.4. (You can check this with CFShow(), which tells you the internal representation.)Caw

© 2022 - 2024 — McMap. All rights reserved.