无法将从本地文件读取的NSData转换为Swift中的字符串输出 [英] Can't convert NSData read from a local file and output as string in Swift

查看:134
本文介绍了无法将从本地文件读取的NSData转换为Swift中的字符串输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个简单的工具来从项目中的文件中读取特定的偏移地址。

Well I am trying to creating a simple tool to read an specific offset address from a file that's within the project.

我可以很好地读取它并获取字节,问题是我想将结果转换为字符串,但我不能。

I can read it fine and get the bytes, the problem is that I want to convert the result into a string, but I just can't.

我的输出是这样的:< 00000100 88000d00 02140dbb 05c3a282>但我希望进入字符串。

My output is this: <00000100 88000d00 02140dbb 05c3a282> but I want into String.

找到一些使用NSData的扩展名的例子,但仍然无效。

Found some examples of doing it using an extension for NSData, but still didn't work.

所以任何人都可以帮忙??

So anyone could help??

以下是我的代码:

Here's my code:

class ViewController: UIViewController {

let filemgr = NSFileManager.defaultManager()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let pathToFile = NSBundle.mainBundle() .pathForResource("control", ofType: "bin")
    let databuffer = filemgr.contentsAtPath(pathToFile!)
    let file: NSFileHandle? = NSFileHandle(forReadingAtPath: pathToFile!)

    if file == nil {
        println("File open failed")
    } else {
        file?.seekToFileOffset(197584)
        let byte = file?.readDataOfLength(16)

        println(byte!)
        file?.closeFile()
    }
  }
}


推荐答案

正确答案在@Martin R对此链接的建议: https://codereview.stackexchange.com/a/86613/35991

The correct answer following @Martin R suggestion to this link: https://codereview.stackexchange.com/a/86613/35991

以下是代码:

Here's the code:

extension NSData {
func hexString() -> String {
    // "Array" of all bytes:
    let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
    // Array of hex strings, one for each byte:
    let hexBytes = map(bytes) { String(format: "%02hhx", $0) }
    // Concatenate all hex strings:
    return "".join(hexBytes)
}

}

我这样使用:

And I used like this:

let token = byte.hexString()

这篇关于无法将从本地文件读取的NSData转换为Swift中的字符串输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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