0

Given a 6 byte array from a specific TLV tag:

unsigned char bytes[] = { 0x00, 0x00, 0x00, 0x01, 0x23, 0x45 };
NSData * data = [NSData dataWithBytes:bytes length:6];

How could one convert it to the decimal number with value of:

12345

I tried finding something that is already implemented in Foundation, but with no luck.

Said Sikira
  • 4,482
  • 29
  • 42

2 Answers2

1
// Step 1: convert data to string
NSMutableString *string = [[NSMutableString alloc] initWithCapacity:data.length];
unsigned char *bytes = [data bytes];
for (NSUInteger i = 0; i < [data length]; i++)
    [string appendFormat:@"%.2x", bytes[i]];

// Step 2: convert string to decimal number
NSDecimalNumber *decimalNumber = [[NSDecimalNumber alloc] initWithString:string];
Willeke
  • 14,578
  • 4
  • 19
  • 47
0

Simply mul and add:

int sum = 0;
for( int c = 0; c<6 c++ )
{
  sum *= 100; // shift up two decimal digits
  sum += bytes[c] & 0xF + 10 * bytes[c] >> 4; // add new digits
}
NSNumber *result = [NSNumber numberWithInt:sum];

Typed in Safari.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50