4

Many/most OSStatus values on iPhone are 4-character displayable values jammed into the 4-byte int. In order to make the values displayable in a hex dump on a little-endian system, the bytes are in reverse order in memory, such that simply copying them to a buffer with memcpy and tagging a null on the end doesn't produce the desired result.

Does anyone have a clever way to swap the bytes around and get them into a character string in a relatively small number of (source code) keystrokes?

2 Answers 2

2

Check out the functions in CFByteOrder.h, such as CFSwapInt32(uint32_t).

If that is not available, just write your own 32-bit byte-swap code, eg:

#define SWAPUINT32(x) (((x & 0xff) << 24) | ((x & 0xff00) << 8) | \
                      ((x & 0xff0000) >> 8) | ((x & 0xff000000) >> 24))

and use it thus:

uint32_t swappedValue = SWAPUINT32(originalValue);
2

Wanting to minimize the amount of coding required (since this is diagnostic/debug code that needs to be kept simple) I opted for a C function that returns an NSString:

NSString* statToString(UInt32 source) {
    char buf[4];
    char* sourceView = (char*) &source;
    buf[0] = sourceView[3];
    buf[1] = sourceView[2];
    buf[2] = sourceView[1];
    buf[3] = sourceView[0];
    return [[[NSString alloc] initWithBytes:buf length:4 encoding:NSUTF8StringEncoding] autorelease];
}

This allows the function to be used directly in an NSLog parameter list, eg, without the need to declare any temps.

Probably could tighten it up by using one of the swab variants, but that level of optimization isn't necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.