Is there any way to store unsigned long in core data?

前端 未结 4 2053
悲&欢浪女
悲&欢浪女 2021-01-06 02:46

CoreData provides Integer 16, Integer 32 and Integer 64 storage, but doesn\'t support any sign qualifiers. You can store an unsigned int (32 bit) as a signed long (64 bit) a

4条回答
  •  臣服心动
    2021-01-06 03:48

    [Previous comment promoted to answer]

    Sounds like it is the bit pattern which is important to you and not the integer value per se. You can store it as a signed - just cast it as C signed<->unsigned casts don't enforce mathematical correctness and just preserve the bits. Cast it back to use it.

    Follow up question:

    In general yes in (Obj-)C(++) you can store an unsigned integer value into a variable with the equivalent signed integer type, and vice-versa. C casts from signed -> unsigned by definition equate to a bit-copy when using 2's complement integers and the two types are the same size. Going the other way, unsigned -> signed, is "implementation defined" - which in practice usually means a bit-copy. Clang & GCC use a bit-copy for both, but if you want to be absolutely certain you can use a union:

    unsigned long r;
    long l;
    
    r = (unsigned long)l; // will always work (cast optional)
    
    // following is l = (long)r (cast optional) without "implementation defined" risk
    { union { long sValue; unsigned long uValue; } tmp; tmp.uValue = r; l = tmp.sValue;}
    

    But seriously I doubt anybody would! (Note: Clang at least will compile it down to a straight assignment (bit-copy).)

提交回复
热议问题