如何将NSData字节转换为NSNumber或NSInteger?
有一个特殊的 NSString
initWithData
方法,用于抓取位并将它们转换为字符串。但是,我没有在 NSNumber
类ref中找到它。目前,我从 NSData
格式的服务器获取原始数据(字节)。我知道如何在C中使用 memcpy
和 int
指针。但我很好奇直接从 NSData
那样做的便利方法。无需转换。例如,我得到 00000010
byte,我需要将其转换为值为2的 NSNumber
,或者 NSInteger 。
There's a special NSString
initWithData
method for grabbing bits and converting them into string. However, I haven't found that in NSNumber
class ref. Currently, I'm getting raw data (bytes) from a server in NSData
format. I know how to do that in C, using memcpy
and int
pointers. But I am curious about what the convenience methods are for doing that straight from NSData
. No conversion is needed. For example, I'm getting 00000010
byte, and I need to turn that into NSNumber
of value 2, or NSInteger
.
NSData
只是一个字节桶,不知道其中包含的数据。 NSString
's initWithData:encoding:
method是此方法的倒数(它正好相反):
NSData
is just a bucket for bytes and has no knowledge of the data contained therein. NSString
's initWithData:encoding:
method is a reciprocal (it does the opposite) of this method:
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
因此,要完全回答您的问题,了解您的号码最初是如何强制转换为 NSData
对象非常重要。一旦你知道编码函数,搜索就是互惠函数。
Therefore, to answer your question fully, it's important to know how your numbers were originally coerced into an NSData
object. Once you know the encoding function, the search is for the reciprocal function.
根据你在问题中所包含的内容,可能有许多不同的解决方案。但是,您可能可以使用以下行中的某些内容在NSData对象上使用 getBytes:length:
转换为可用的数字格式。例如。
From what you've included in the question, there may be a number of different solutions. However, you'll probably be able to use something along the following lines to convert into a usable numeric format using getBytes:length:
on your NSData object. For e.g.
NSUInteger decodedInteger;
[myDataObject getBytes:&decodedInteger length:sizeof(decodedInteger)];
您可以将 decodingInteger
的类型更改为适用于 NSData
对象中的字节的任何内容。
You can change the type of decodedInteger
to whatever is appropriate for the bytes in your NSData
object.