Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

iphone - Bit conversion tool in Objective-C

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*.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...