NSString 到 NSData 转换为十六进制值 [英] NSString to NSData conversion to Hex Value
问题描述
我一直在尝试将用户默认值 NSString(也尝试过 NSData)转换为可以与 char 数组一起使用的十六进制值.问题是,每次我从 NSString 或 NSData 转换它时,它都会采用十六进制值并将它们转换为 ASCII 值,这根本不是我想要的.我如何告诉它从字面上获取那里的值并将它们保持为十六进制?我正在努力寻找解决方案.
I've been trying to convert a user defaults NSString (tried NSData also), into a hex value I can use with char array. the problem is that every time I convert it from the NSString or NSData it takes the hex values and turns them into ASCII values, which isn't what I want at all. how to I tell it to literally take the values that are there and keep them hex? I'm struggling to find a solution.
在我的 .plist 内
inside my .plist
<key>shit</key>
<string>5448495344414e475448494e474e45454453544f53544159484558</string>
我将 NSString 转换为 NSData 的代码
my code to convert the NSString to NSData
NSString *defaults = [[NSUserDefaults standardUserDefaults] objectForKey:@"shit"];
NSData *theData = [defaults dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [theData length];
Byte *byteData = (Byte*)malloc(dataLength);
memcpy(byteData, [theData bytes], len);
NSLog(@"THIS : %@",[NSData dataWithBytes:byteData length:len]);
输出:
THIS : <35343438 34393533 34343431 34653437 35343438 34393465 34373465 34353435 34343533 35343466 35333534 34>len
它到底为什么要这样做?我想要原始的十六进制值,而不是对我的十六进制值的解释.
why in the world is it doing this? I want the original hex values, not interpretation of my hex values.
推荐答案
字节既不是十六进制也不是 ascii 也不是八进制也不是 int 也不是浮点等,它们只是显示和/或思考字节的不同方式.NSLog
显示对象的方式由编写对象的description
方法的方式决定.因此,NSData
和 NSString
的 NSLog
以不同的方式显示相同的字节.
A byte is neither hex nor ascii nor octal nor int nor float, etc, they are just different ways to display and/or think about a byte(s). The way NSLog
displays objects is dictated by the way the objects's description
method is written. Thus NSLog
of NSData
and NSString
display the same bytes differently.
如果您想访问 NSData
中的字节,只需直接访问它们:theData.bytes,无需
memcpy`.
If you want access to the bytes in an NSData
just access them directly: theData.bytes, no need to
memcpy`.
最后也是最重要的:你想完成什么?
Lastly and most importantly: What are you trying to accomplish?
通过阅读一本关于C"语言的好书并学习它,新开发人员会得到很好的服务——这就是我所做的.
New developers are well served by getting a good book on the "C" language and studying it--that is what I did.
这篇关于NSString 到 NSData 转换为十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!