NSString(十六进制)到字节
Objective-C 中是否有任何方法可以将十六进制字符串转换为字节?例如,@"1156FFCD3430AA22"
到 无符号字符数组 {0x11, 0x56, 0xFF, ...}
。
Is there any method in Objective-C that converts a hex string to bytes? For example @"1156FFCD3430AA22"
to an unsigned char array {0x11, 0x56, 0xFF, ...}
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我能想到的最快的 NSString 类别实现(一些示例的混合物):
它比 wookay 的解决方案快了近 8 倍。 NSScanner 相当慢。
Fastest NSString category implementation that I could think of (cocktail of some examples):
It is close to 8 times faster than wookay's solution. NSScanner is quite slow.
scanHexInt:
和NSScanner
的类似方法可能有助于执行您想要的操作,但您可能需要打破首先将其串成较小的块,在这种情况下,手动进行翻译可能比使用 NSScanner 更简单。The
scanHexInt:
and similar methods ofNSScanner
might be helpful in doing what you want, but you'd probably need to break the string up into smaller chunks first, in which case doing the translation manually might be simpler than usingNSScanner
.不是以你正在做的方式。您需要编写自己的方法来获取每两个字符,将它们解释为 int,并将它们存储在数组中。
Not in the way you are doing it. You'll need to write your own method to take every two characters, interpret them as an int, and store them in an array.
修改方法,
Modified approach,
Swift 2.2 中的首次尝试:
或者,作为 String 的扩展:
这是一项持续进行中的工作,但到目前为止似乎运行良好。
进一步的优化和更深入的讨论可以在代码审查中找到。
First attempt in Swift 2.2:
Or, as an extension on String:
This is a continuous work-in-progress, but appears to work well so far.
Further optimizations and a more in-depth discussion can be found on Code Review.
如果字符串像这样返回错误值的几种解决方案
“DBA”
“DBA”字符串的正确数据为 “\x0D\xBA”(int 值:3514)
如果您获得了数据, 不是这样的“\x0D\xBA”这意味着你得到了一个错误的字节,因为值会不同,例如你得到了这样的数据“\xDB\x0A” > int 值为 56074
这里重写解决方案:
Several solution is returned wrong value if the string like this
"DBA"
The correct data for "DBA" string is "\x0D\xBA" (int value : 3514)
if you got a data is not like this "\x0D\xBA" it mean you got a wrong byte because the value will be different, for example you got data like this "\xDB\x0A" the int value is 56074
Here is rewrite the solution: