如何将NSData的十六进制字符串转换为正常的十六进制字符串? [英] How can I turn NSData's hex string into a normal hex string?

查看:386
本文介绍了如何将NSData的十六进制字符串转换为正常的十六进制字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



从这个网站: http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html



我得到的十六进制值是:FF7FFFFF



但是,如果我把这个int放入NSData中,就像这样:

  // // unsigned int是unsignedInt,其长度是unsignedLength 

NSData * thisData = [NSData dataWithBytes:& unsignedInt length:unsignedLength];

然后使用描述方法,它应该以字符串形式返回数据的十六进制值:

  NSLog(@data as hex:%@,[thisData description]); 

输出结果为:

 数据为十六进制:< ffff7fff> 

同一网站上的评估结果为4294934527。



因此,NSData似乎使用了一些非标准的十六进制格式。任何人都可以告诉我如何恢复到真正的十六进制格式?

解决方案

你看到存储字节 unsigned int 在big-endian和little-endian之间。



如果你想保证 NSData 为big-endian格式,那么您应该执行以下操作:

  unsigned int x = 4286578687; 
unsigned int big = NSSwapHostIntToBig(x);
NSData * thisData = [NSData dataWithBytes:& big length:sizeof(big)];
NSLog(@data as hex:%@,thisData);

这将数据的预期结果记录为十六进制:< ff7fffff>



此代码适用于任何处理器类型,并始终以big-endian格式给出结果。



当以另一种方式返回时,您需要使用 NSSwapBigIntToHost 函数来确保将大端数据正确转换为本地格式。 / p>

So, take an unsigned int, say 4286578687.

From this site: http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html

I get the hex value to be: FF7FFFFF

However, if I put that int into NSData like so:

//The unsigned int is unsignedInt and its length is unsignedLength 

NSData *thisData = [NSData dataWithBytes:&unsignedInt length:unsignedLength];

And then use the description method, which supposedly returns the data's hex value as a string:

NSLog(@"data as hex: %@", [thisData description]);

The output is:

data as hex: <ffff7fff>

Which on the same website evaluates to 4294934527.

So it seems like NSData is using some non-standard hex format. Can anyone tell me how to get back to the real hex format?

解决方案

You are seeing a difference between storing the bytes of the unsigned int in big-endian versus little-endian.

If you want to guarantee that the output of the NSData is in big-endian format then you should do the following:

unsigned int x = 4286578687;
unsigned int big = NSSwapHostIntToBig(x);
NSData *thisData = [NSData dataWithBytes:&big length:sizeof(big)];
NSLog(@"data as hex: %@", thisData);

This logs the expected result of data as hex: <ff7fffff>.

This code will work on any processor type and always give you the result in big-endian format.

When going back the other way you would need to use the NSSwapBigIntToHost function to ensure the big-endian data is properly converted to the local format.

这篇关于如何将NSData的十六进制字符串转换为正常的十六进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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