简体   繁体   中英

Can't convert NSData read from a local file and output as string in 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.

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

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()
    }
  }
}

So long as you know the encoding, you can create a string from an NSData object like this

let str = NSString(data: data, encoding: NSUTF8StringEncoding)

By the way, you might want to try using if let to unwrap your optionals rather than force-unwrapping, to account for failure possibilities:

let filemgr = NSFileManager.defaultManager()
if let pathToFile = NSBundle.mainBundle() .pathForResource("control", ofType: "bin"),
       databuffer = filemgr.contentsAtPath(pathToFile),
       file = NSFileHandle(forReadingAtPath: pathToFile)
{
    file.seekToFileOffset(197584)
    let bytes = file.readDataOfLength(16)
    let str = NSString(data: bytes, encoding: NSUTF8StringEncoding)
    println(str)
    file.closeFile()
}
else {
    println("File open failed")
}

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM