xcode Swift 将字节数组转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35620543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:35:05 来源:igfitidea点击:
Swift converting Byte Array into String
提问by nik
I can't convert this below byte array into String in swift.
我无法将下面的字节数组快速转换为字符串。
let chars: [UInt8] = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0]
let datastring = NSString(data: chars, encoding: NSUTF8StringEncoding)
But in android it just works fine I don't know whats wrong in swift.
但在 android 中它运行良好,我不知道 swift 有什么问题。
回答by vadian
[UInt8]
is not NSData
, so you can't use the NSString(data...
initializer
[UInt8]
不是NSData
,所以你不能使用NSString(data...
初始化程序
You might use
你可能会用
let chars: [UInt8] = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0]
let count = chars.count / sizeof(UInt8)
let datastring = NSString(bytes: chars, length: count, encoding: NSASCIIStringEncoding)
回答by Kacper Dziubek
In Swift 3 you can use this:
在 Swift 3 中你可以使用这个:
import Foundation
let chars: [UInt8] = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0]
let string = String(data: Data(chars), encoding: .utf8)