NSDecimal equal to NSDecimalNumber?

I am looking for an efficient way to store NSDecimalNumber

with other data in a buffer NSData

.

I haven't found a way to do this directly from NSDecimalNumber

. However, it can be easily converted with:

NSDecimal value = [theDecimalNumber decimalValue];

      

And it's not hard to transfer NSDecimal

to memory (20 bytes).

But, my question is: Are the NSDecimalNumber

and values NSDecimal

the same?

Since their declarations have some differences ( ExternalRefCount

?):

@interface NSDecimalNumber : NSNumber {
@private
    signed   int _exponent:8;
    unsigned int _length:4;
    unsigned int _isNegative:1;
    unsigned int _isCompact:1;
    unsigned int _reserved:1;
    unsigned int _hasExternalRefCount:1;
    unsigned int _refs:16;
    unsigned short _mantissa[0]; /* GCC */
}

typedef struct {
    signed   int _exponent:8;
    unsigned int _length:4;     // length == 0 && isNegative -> NaN
    unsigned int _isNegative:1;
    unsigned int _isCompact:1;
    unsigned int _reserved:18;
    unsigned short _mantissa[NSDecimalMaxSize];
} NSDecimal;

      

Is it possible to do many transfers between the two without losing precision?

+3


source to share


2 answers


I have done numerous calculations going from one to the other without any problem. So I think we can say that they fit as identical.

I expand NSDecimalNumber

with



#define DecNum_SizeOf   20

+ (NSDecimalNumber *) fromPtr:(void *)ptr
{
    NSDecimal valueRead;
    memcpy (&valueRead, ptr, DecNum_SizeOf);
    return [NSDecimalNumber decimalNumberWithDecimal:valueRead];
}

- (void) toPtr:(void *)ptr
{
    NSDecimal valueWrite = [self decimalValue];
    memcpy (ptr, &valueWrite, DecNum_SizeOf);
}

      

Waiting for a more "standard" method to do the job also

0


source


Have you tried using class methods NSArchiver

?



NSData *data=[NSArchiver archivedDataWithRootObject:yourNumber];

      

0


source







All Articles