Bit conversion tool in Objective-C

為{幸葍}努か 提交于 2019-11-28 05:28:45

问题


Are there any built in utilities or macros in the objective-c libraries for iOS that will allow you to convert bytes to and from integers with respect to endianess?

Please don't tell me to use bit-shifting operations. I am trying to avoid writing custom code to do this if it already exists.

I would like the code to convert NSData* to primitive types (int, uint, short, etc) and to convert primitive types back to NSData*.


回答1:


You can get the bytes from NSData by accessing the bytes property. Then just cast that to a pointer to whatever type you want. Obviously you'll need to ensure you know the endianness and size of what is in your NSData.

e.g.

#include <CFByteOrder.h>

// Bytes to uint32_t
NSData *data = <THE_DATA>;
void *bytes = [data bytes];
uint32_t *intBytes = (NSInteger*)bytes;
uint32_t swapped = CFSwapInt32BigToHost(*intBytes); ///< If the data in `data' is big endian

// uint32_t to bytes
uint32_t someInt = 1234;
uint32_t swappedInt = CFSwapInt32HostToBig(someInt); ///< If we want to store in big endian
NSData *data = [NSData dataWithBytes:&swappedInt length:sizeof(swappedInt)];



回答2:


I think you want the CFSwapInt32* family of functions.

See Apple's docs.



来源:https://stackoverflow.com/questions/8552864/bit-conversion-tool-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!