简体   繁体   中英

NSData to String in Swift

My NSData length is 20 bytes. Like

<7FFF7FFF 7FFF7FFF 7FFF7FFF 7FFF7FFF 7FFF7FFF>

But every time when it runs to this code would return nil.

let stringData: String = NSString(data: nsdata, encoding: NSUTF8StringEncoding) as String

Can anybody help me solve this question?

Thanks.

You can use .description() on nsdata variable to get exact same string as above: "<7FFF7FFF 7FFF7FFF 7FFF7FFF 7FFF7FFF 7FFF7FFF>":

nsdata.description() 

but is that really what you want? Maybe you want to parse it or something like that? For that kind of solution you will need to provide more deatils.

Converted from hex to string I get: "ÿÿÿÿÿÿÿÿÿÿ" so I assume that this is some kind of message that you want to decode.

EDIT:

You could extract bytes into the array with:

Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))

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