Search code examples
iosobjective-ccocoa-touchnsdata

Convert NSData to unsigned int 32 array


I want to convert the 8 bytes I have in an NSData instance to a uint32_t array that has 2 items. I did the following, but it's not correct.

NSLog(@"Challenge data %@",dataChallenge);
uint32_t *data = (uint32_t *)dataChallenge.bytes;
NSLog(@"data0: %08x, data1: %08x", data[0], data[1]);

And this is the result:

Challenge data <3ce3e664 dafda14b>
data0: 64e6e33c, data1: 4ba1fdda

The order of data is not correct.

The values should be:

Challenge data <3ce3e664 dafda14b>
data0: 3ce3e664, data1: dafda14b

Solution

  • uint32_t *data = (uint32_t *)dataChallenge.bytes;

    Example:

    NSData *dataChallenge = [@"12345678" dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"dataChallenge: %@", dataChallenge);
    uint32_t *data = (uint32_t *)dataChallenge.bytes;
    NSLog(@"data0: %08x, data1: %08x", data[0], data[1]);
    

    NSLog output:

    dataChallenge: <31323334 35363738>
    data0: 34333231, data1: 38373635

    Note: The bytes are reversed because this is a lithe-endian machine

    With memcpy:

    NSData *dataChallenge = [@"12345678" dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"dataChallenge: %@", dataChallenge);
    uint32_t data[2];
    memcpy(data, (uint32_t *)dataChallenge.bytes, dataChallenge.length);
    NSLog(@"data0: %08x, data1: %08x", data[0], data[1]);
    

    NSLog output:

    dataChallenge: <31323334 35363738>
    data0: 34333231, data1: 38373635

    Swapping the byte order:

    NSLog(@"data0: %08x, data1: %08x", CFSwapInt32BigToHost(data[0]), CFSwapInt32BigToHost(data[1]));
    

    NSLog output:

    data0: 31323334, data1: 35363738

    Note: See CFByteOrder.h for more combinations of byte swapping.