将 NSString 转换为 NSData 而不更改数据
我有一个包含一系列十六进制值的 NSString,例如:
6173736e 616d65a2 15165570 6f696e74 584e534f 626a6563
但是,我需要将这个完全相同的数据放在 NSData 对象中。我尝试过做以下事情:
mydata = [mystring dataUsingEncoding:NSASCIIStringEncoding]; //尝试过各种编码选项
无论我做什么,mydata
永远不会包含与NSString相同的值,这正是我所需要的。
非常感谢任何帮助!谢谢。
I have an NSString that contains a series of hex values, for example:
6173736e 616d65a2 15165570 6f696e74 584e534f 626a6563
However, I need this exact same data to be in an NSData object. I have tried doing things such as:
mydata = [mystring dataUsingEncoding:NSASCIIStringEncoding];
//have tried all kind of encoding options
Regardless of what I do though, mydata
never contains the same values the NSString had, which is what I need.
Would greatly appreciate any help! Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您似乎误解了该方法的作用。它不会解析字符串以获取数字的十六进制表示形式;它只是创建一个数据对象,表示具有特定字节编码的字符串。因此,在您的情况下,数据将包含值为 54(“6”的 ASCII 值)、49(“1”)、55(“7”)、51(“3”)、55( '7')、51('3')、54('6')、101('e')等。
如果要解析十六进制字符串,可以使用 NSScanner 扫描十六进制值。
这是您想要的基本形式:(
警告:在浏览器中编写,尚未测试它,如果您尝试用它运行核反应堆,可能会导致崩溃等)
You seem to misunderstand what that method does. It doesn't parse the string for hexadecimal representations of numbers; it just creates a data object that represents the string with a certain byte encoding. So in your case, the data will contain bytes with the values 54 (the ASCII value for '6'), 49 (for '1'), 55 (for '7'), 51 (for '3'), 55 (for '7'), 51 (for '3'), 54 (for '6'), 101 (for 'e') and so on.
If you want to parse hexadecimal strings, you can use NSScanner to scan for hex values.
Here's the basic form of what you want:
(Warning: Written in browser, haven't tested it, might cause a meltdown if you try to run a nuclear reactor with it, etc.)
以第一个字符
6
为例。6
字符的十六进制值(0x360d0a,根据此链接,里程可能因编码而异)与十六进制值 0x6 不同。你已经得到的似乎是数据,尽管我不确定如何再次准确地写入该数据。
你可能不得不求助于类似的东西:
Taking the first character
6
as an example.The hex value for
6
the character (0x360d0a according to this link, milage may vary depending on encoding) isn't the same as the hexvalue 0x6.What you've got already appears to be data, though I'm not sure how you can write that data exactly again.
You may have to resort to something like:
我知道参加聚会迟到了,但我最近遇到了类似的问题,从詹姆斯·韦伯斯特的回答开始,得出了这个:
Late to the party I know, but I recently had a similar problem, started with James Webster's answer and arrived at this: