How to convert NSData bytes into NSNumber or NSInteger?

微笑、不失礼 提交于 2019-12-02 02:04:08
ikuramedia

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.

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.

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.

Jeevanantham Balusamy

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

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