How to convert NSData bytes into NSNumber or NSInteger?

荒凉一梦 提交于 2019-12-02 00:50:25

问题


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.


回答1:


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

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.

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

You can change the type of decodedInteger to whatever is appropriate for the bytes in your NSData object.




回答2:


Try this:

NSNumber *num = [NSKeyedUnarchiver unarchiveObjectWithData:numberAsNSData]; 

Edit:

As pointed out by Matthias Bauch this will not work in your case. This only works if your NSNumber object was archived into NSData objects.




回答3:


NSString to the rescue:

const unsigned char *bytes = [serverData bytes];
NSInteger aValue = [NSString stringWithFormat:@"%2x", bytes[0]].integerValue;

The docs warn about using NSScanner for localized decimal numbers, but that's of no concern in this case.




回答4:


Here is the answer

//Integer to NSData
+(NSData *) IntToNSData:(NSInteger)data
{
    Byte *byteData = (Byte*)malloc(4);
    byteData[3] = data & 0xff;
    byteData[2] = (data & 0xff00) >> 8;
    byteData[1] = (data & 0xff0000) >> 16;
    byteData[0] = (data & 0xff000000) >> 24;
    NSData * result = [NSData dataWithBytes:byteData length:4];
    NSLog(@"result=%@",result);
    return (NSData*)result;
}

refer https://stackoverflow.com/a/20497490/562812 for more detail



来源:https://stackoverflow.com/questions/9224712/how-to-convert-nsdata-bytes-into-nsnumber-or-nsinteger

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