在不改变数据的情况下将 NSString 转换为 NSData [英] Converting NSString to NSData without changing data

查看:59
本文介绍了在不改变数据的情况下将 NSString 转换为 NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一系列十六进制值的 NSString,例如:

I have an NSString that contains a series of hex values, for example:

6173736e 616d65a2 15165570 6f696e74 584e534f 626a6563

6173736e 616d65a2 15165570 6f696e74 584e534f 626a6563

但是,我需要在 NSData 对象中包含完全相同的数据.我试过做这样的事情:

However, I need this exact same data to be in an NSData object. I have tried doing things such as:

mydata = [mystring dataUsingEncoding:NSASCIIStringEncoding];//尝试了各种编码选项

mydata = [mystring dataUsingEncoding:NSASCIIStringEncoding]; //have tried all kind of encoding options

不管我做什么,mydata 永远不会包含与 NSString 相同的值,这正是我所需要的.

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.

推荐答案

您似乎误解了该方法的作用.它不解析数字的十六进制表示的字符串;它只是创建一个数据对象,该对象表示具有特定字节编码的字符串.因此,在您的情况下,数据将包含值为 54(6"的 ASCII 值)、49(1")、55(7")、51(3")、55(对于7")、51(对于3")、54(对于6")、101(对于e")等等.

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.

如果你想解析十六进制字符串,你可以使用 NSScanner 来扫描十六进制值.

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:

NSScanner *scanner = [NSScanner scannerWithString:yourHexString];
NSMutableData *data = [NSMutableData data];
while (![scanner isAtEnd]) {
    unsigned value;
    if ([scanner scanHexInt:&value]) {
        [data appendBytes:&value length:sizeof(value)];
    } else {
        NSLog(@"Invalid value in scanned string");
    }
}

(警告:写在浏览器中,没有测试过,如果你试图用它运行核反应堆可能会导致崩溃等)

(Warning: Written in browser, haven't tested it, might cause a meltdown if you try to run a nuclear reactor with it, etc.)

这篇关于在不改变数据的情况下将 NSString 转换为 NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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