[英]Can't compare NSData header to string in Swift
I am trying to compare the header (first bytes of NSData) against a string, I can successfully print the string, but comparing doesn't work. 我正在尝试将标头(NSData的第一个字节)与一个字符串进行比较,我可以成功打印该字符串,但是无法进行比较。
This is what I've tried: 这是我尝试过的:
var dataHeader:NSString = NSString(bytes: data.bytes, length: min(data.length, 8), encoding: NSASCIIStringEncoding)!
println(dataHeader)
result: PK
The ASCII of "PK" is 0x50 0x4B. “ PK”的ASCII为0x50 0x4B。
When I try the following, nothing happens: 当我尝试以下操作时,没有任何反应:
if dataHeader == "PK" {
}
Maybe I'm a noob but I don't have any ideas left, so does anyone have an idea on how to solve this? 也许我是菜鸟,但是我没有任何想法,所以有人对如何解决这个问题有想法吗? I am guessing it has something to do with the string encoding, but after doing a lot of research, I still can't figure it out.
我猜想它与字符串编码有关,但是经过大量研究后,我仍然无法弄清楚。
Any help is appreciated, thanks! 任何帮助表示赞赏,谢谢!
Is it possible there are other non-printing characters after the "PK" if this is binary data? 如果是二进制数据,是否可能在“ PK”之后还有其他非打印字符? What's the length of the string
dataHeader
? 字符串
dataHeader
的长度是dataHeader
?
If there are other funny characters after, you can truncate the string or use NSString's hasPrefix:
method: 如果之后还有其他有趣的字符,则可以截断字符串或使用NSString的
hasPrefix:
方法:
if dataHeader.hasPrefix("PK") {
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.