NSDecimal equal to NSDecimalNumber value?

268 views Asked by At

I am looking for an effective way to save NSDecimalNumber with other data in NSData buffer.

I have not found a method to do it directly from NSDecimalNumber. However, it is easy to convert it with :

NSDecimal value = [theDecimalNumber decimalValue];

And it is not difficult to transfer NSDecimal in memory (20 bytes).

But, my question: The NSDecimalNumber and NSDecimal values are they exactly the same?

Because 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 perform many transfers between the two type, without any loss of precision ?

2

There are 2 answers

0
Croises On BEST ANSWER

I made numerous calculations with the transfer from one to the other without any problems. So I think we can say that they are suitable as identical.

I extend 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);
}

While awaiting a method more "standard" to perform the job as well

1
Daniyar On

Did you try to use NSArchiver class methods?

NSData *data=[NSArchiver archivedDataWithRootObject:yourNumber];