Kevin Kevin - 4 months ago 15
Objective-C Question

More elegant alternative to (*(uint16_t*)[[NSData] bytes])?

I need to byte swap some bytes that represent an unsigned 16 bit integer. The following code works, but seems a bit ridiculous:

CFSwapInt16(*(uint16_t*)[[myNSDataVariable] bytes]);


Here's what I've deduced is going on:

[[myNSDataVariable] bytes]
returns a void pointer to a byte array.

The
(uint16_t*)
casts the void pointer to a
uint16_t
pointer.

The final outer
*
dereferences the
uint16_t
pointer, providing access to the actual
uint16_t
value.

Is there a more elegant way to get the
uint16_t
value from
NSData
?

Answer

I'd say the following is more readable:

uint16_t *valuePtr = (uint16_t *)[myNSDataVariable bytes];
uint16_t swappedValue = CFSwapInt16(*valuePtr);

But ultimately you're going to do this conversion somewhere. If you're doing it more than once, I'd recommend a function to make it clearer:

uint16_t SwappedIntegerFromData(NSData *data) {
    uint16_t *valuePtr = (uint16_t *)[data bytes];
    return CFSwapInt16(*valuePtr);
}

uint16_t value = SwappedIntegerFromData(myNSDataVariable);

But again, the conversions have to go somewhere.