The Shape of Everything
A website mostly about Mac stuff, written by August "Gus" Mueller
» Acorn
» Retrobatch
» Mastodon
» Instagram
» Github
» Maybe Pizza?
» Archives
» Feed
» Micro feed
September 14, 2018

I've been working on new JavaScript to C/Cocoa bridge lately, for fun and education. And I made an interesting discovery today- NSNumber stores shorts and unsigned chars the same. Is this a bug in NSNumber? Consider the following code:

printf("@encode(short) %s, %s, %c, %lu\n",
        [[NSNumber numberWithShort:'a'] objCType],

printf("@encode(char) %s, %s, %c, %lu\n", 
        [[NSNumber numberWithChar:'a'] objCType],

printf("@encode(unsigned char) %s, %s, %c, %lu\n", 
        @encode(unsigned char),
        [[NSNumber numberWithUnsignedChar:'a'] objCType],
        sizeof(unsigned char));


@encode(short) s, s, s, 2
@encode(char) c, c, c, 1
@encode(unsigned char) C, s, C, 1

I'd love to update this post if anyone has any ideas why this happens.

OK here's that update:
NSNumber is most likely built on top of CFNumber. And CFNumber doesn't support unsigned char- so it bumps the storage up to a signed short (from 8 bits to 16) in order to keep from rounding over. The same thing occurs for unsigned int:

printf("@encode(int) %s, %s, %c, %lu\n",
        [[NSNumber numberWithInt:1] objCType],

printf("@encode(unsigned int) %s, %s, %c, %lu\n",
        @encode(unsigned int),
        [[NSNumber numberWithUnsignedInt:1] objCType],
        sizeof(unsigned int));

printf("@encode(long long) %s, %s, %c, %lu\n",
        @encode(long long),
        [[NSNumber numberWithLongLong:1] objCType],
        sizeof(long long));


@encode(int) i, i, i, 4
@encode(unsigned int) I, q, I, 4
@encode(long long) q, q, q, 8

Why long long and not long? Because on 64 bit sizeof(long) is the same as sizeof(long long)