3

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 ?

Croises
  • 18,570
  • 4
  • 30
  • 47

2 Answers2

0

Did you try to use NSArchiver class methods?

NSData *data=[NSArchiver archivedDataWithRootObject:yourNumber];
Daniyar
  • 2,975
  • 2
  • 26
  • 39
  • Yes. On iOS there is no NSArchiver, but only NSKeyedArchiver (?) And data.length == 451 to 458 bytes !!! vs 20 for NSDecimal... – Croises Nov 27 '14 at 11:41
0

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

Croises
  • 18,570
  • 4
  • 30
  • 47