How to reverse byte order of NSInteger or NSUInteger in objective-c

This is somewhat after this publication , but with a different question, so I felt that I should ask in a separate topic.

I am at the point where I have four consecutive bytes in memory that I read from a file. I would like to save them as a bitmap (the actual int value of them doesn't matter until it appears). When I print what is in my int, I notice that it seems to be stored in the reverse order (small end).

Does anyone have a good method for reordering bytes. Then, once, reverse, choosing consecutive bits spanning two bytes and returning back to int?

unsigned char data[] = { 0x00, 0x02, 0x45, 0x28 }; NSInteger intData = *((NSInteger *)data); NSLog(@"data:%08x", intData); // data:28450200 
+6
objective-c endianness byte bytearray nsinteger
source share
1 answer

Cocoa (or rather, the framework) has functions for replacing bytes of bytes: NSSwapInt , NSSwapShort , NSSwapLong and NSSwapLongLong . They exchange bytes regardless of what they make big-endian integers from small numbers and vice versa.

If you know what format you have, there are other functions that change it to an internal entity: NSSwapLittleIntToHost and NSSwapBigIntToHost . There are also inverse functions that change from native format to small or large format: NSSwapHostIntToLittle and NSSwapHostIntToBig . They are available for other integer types and floating point types. What they do, they are called primitive swap functions for values, if necessary. Thus, NSSwapLittleIntToHost does nothing, and NSSwapBigIntToHost returns the result of NSSwapInt on the small destination machine.

Note that they take parameters of integer types of compilers, not of type NSInteger . Therefore, depending on whether you are creating 32-bit or 64-bit code, you need to use different functions if you use NSInteger .

You should also not drop an array of bytes onto an integer pointer and cast it. It would be better to collect an integer using bit shift operations. Your code will only work if NSInteger is 32 bits wide. If it is 64 bits, then your number will be garbage or your program may even crash. But even if you use an integer type that always has a width of 32 bits ( int32_t from the header C99 <stdint.h> , for example), this may not work as expected.

+15
source share

All Articles