在Objective-C位转换工具 [英] Bit conversion tool in Objective-C

查看:172
本文介绍了在Objective-C位转换工具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有建于Objective-C的库实用程序或宏iOS设备将允许你转换为字节,并从相对于整数ENDIANESS?

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?

请不要告诉我用比特移位操作。我试图避免编写自定义的code这样做,如果它已经存在。

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.

我想code到NSData的*转换为原始类型(INT,UINT,短路等)和原始类型转换回的NSData *。

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

推荐答案

您可以通过访问字节获得的NSData 字节属性。然后,只投了一个指针,以任何你想要的类型。显然,你需要确保你知道什么是字节顺序和大小的的NSData

例如

#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)];

这篇关于在Objective-C位转换工具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆