果断的青椒 · 使用three.js 画渐变的直线_其它_脚本之家· 6 月前 · |
忐忑的牛排 · Docker之Cgroup对于CPU,内存, ...· 9 月前 · |
儒雅的红豆 · 【预测模型】基于蝙蝠算法优化最小二乘支持向量 ...· 1 年前 · |
气宇轩昂的香烟 · 02. bootstrap导航栏居中 - ...· 1 年前 · |
我在swift中将
UInt8
字节数组转换为字符串时遇到了问题。我已经找到了一个简单的解决方案
String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)
但它显示错误
String.type
没有成员
stringWithBytes
。有人能给我一个解决方案吗?
这是我的代码,我得到一个
NSData
,并将其转换为字节数组,然后我必须将该字节数组转换为字符串。
let count = data.length / sizeof(UInt8)
var array = [UInt8](count: count, repeatedValue: 0)
data.getBytes(&array, length:count * sizeof(UInt8))
String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)
"MSString(bytes:,length:,encoding:)“在2015年7月26日似乎无法工作
将字节值转换为ASCII似乎是有问题的,如果你遇到了困难,你可以像下面这样做(也许我在swift中遗漏了一些东西,但我无法在我的时间范围内找到任何解决方案)。这将通过两个函数来完成。第一个函数接受UInt8并将其转换为"\u{}“表示形式,然后由该函数返回。其次,设置另一个函数,该函数接受一个UInt8数组作为参数,然后输出一个字符串。
步骤1.函数将每个字节转换为"\u{someNumber}“
func convertToCharacters(#UInt8Bits : UInt8) -> String {
var characterToReturn : String
switch UInt8Bits{
case 0x00: characterToReturn = "\u{0}"
case 0x01: characterToReturn = "\u{1}"
case 0x02: characterToReturn = "\u{2}"
case 0x03: characterToReturn = "\u{3}"
case 0x04: characterToReturn = "\u{4}"
//..根据需要添加任意数量的字符...不要忘记以16为基数..
case 0x09: characterToReturn = "\u{09}"
case 0x0A: characterToReturn = "\u{0A}"
default: characterToReturn = "\u{0}"
/*..一直到0xff */
case 0xFE: characterToReturn = "\u{FE}"
case 0xFF: characterToReturn = "\u{FF}"
}
return characterToReturn
}
Step #2 ...Next一个函数,该函数接受一个UInt8数组作为参数,然后返回一个字符串...
func UInt8ArrayToString(#UInt8Array: [UInt8]) -> String {
var returnString : String = ""
for eachUInt8Byte in UInt8Array {
returnString += convertToCharacter(UInt8Bits: eachUInt8Byte)
}
return returnString
}
这应该可以在Swift Playground中创建一个数组
var myArray : UInt8 = 0x30、0x3A、0x4B
//然后应用上面的函数
println(UInt8ArrayToString(UInt8Array: myArray))
这个解决方案是可行的。
NSString(bytes: data!, length: data!.count, encoding: NSUTF8StringEncoding)
不是很优雅,也不是“Swifty”,但这很简单,而且很管用:
let i: UInt8 = 65
let s = String(format: "%c", i) // A
我浪费了几个小时寻找一种简单的方法来做这件事,然后我突然想到了我的Unix脚本时代的“printf”!
这对我很有效:
String(bytes: bytes, encoding: NSUTF8StringEncoding)
https://stackoverflow.com/a/29644387/2214832 中的Martin R回答了Sunil Kumar关于他的问题,但没有回答主题问题。如果你已经有了UInt8字节数组,并且需要把它表示为字符串,这个问题仍然会出现。
以下是我的解决方案:
extension String {
init(_ bytes: [UInt8]) {
self.init()
for b in bytes {
self.append(UnicodeScalar(b))
}
使用此扩展,您现在可以使用UInt8字节数组初始化字符串,如下所示:
func testStringUInt8Extension() {
var cs : [UInt8] = []
for char : UInt8 in 0..<255 {
cs.append(char)
print("0..255 string looks like \(String(cs)))")
}
这不是理想的解决方案,因为实际上您需要对UTF-8编码的文本进行解码。但对于ASCII数据,这是预期的。
Swifty解决方案
array.reduce("", combine: { $0 + String(format: "%c", $1)})
十六进制表示法:
array.reduce("", combine: { $0 + String(format: "%02x", $1)})
Swift 2和3的完整示例:
import Foundation
let bytes : [UInt8] = [72, 73]
let nsdata = NSData(bytes: bytes as [UInt8], length: 2)
let str = String(data: nsdata, encoding: NSUTF8StringEncoding)! // 'HI'
下面是一些更通用的代码,用于从字节数组中提取字符串,其中字符串已以UTF-8编码。
/// Class which encapsulates a Swift byte array (an Array object with elements of type UInt8) and an
/// index into the array.
open class ByteArrayAndIndex {
private var _byteArray : [UInt8]
private var _arrayIndex = 0
public init(_ byteArray : [UInt8]) {
_byteArray = byteArray;
/// Method to get a UTF-8 encoded string preceded by a 1-byte length.
public func getShortString() -> String {
return getTextData(getUInt8AsInt())
/// Method to get a UTF-8 encoded string preceded by a 2-byte length.
public func getMediumString() -> String {
return getTextData(getUInt16AsInt())
/// Method to get a UTF-8 encoded string preceded by a 4-byte length. By convention a length of
/// -1 is used to signal a String? value of nil.
public func getLongString() -> String? {
let encodedLength = getInt32()
if encodedLength == -1 {
return nil
return getTextData(Int(encodedLength))
/// Method to get a single byte from the byte array, returning it as an Int.
public func getUInt8AsInt() -> Int {
return Int(getUInt8())
/// Method to get a single byte from the byte array.
public func getUInt8() -> UInt8 {
let returnValue = _byteArray[_arrayIndex]
_arrayIndex += 1
return returnValue
/// Method to get a UInt16 from two bytes in the byte array (little-endian), returning it as Int.
public func getUInt16AsInt() -> Int {
return Int(getUInt16())
/// Method to get a UInt16 from two bytes in the byte array (little-endian).
public func getUInt16() -> UInt16 {
let returnValue = UInt16(_byteArray[_arrayIndex]) |
UInt16(_byteArray[_arrayIndex + 1]) << 8
_arrayIndex += 2
return returnValue
/// Method to get an Int32 from four bytes in the byte array (little-endian).
public func getInt32() -> Int32 {
return Int32(bitPattern: getUInt32())
/// Method to get a UInt32 from four bytes in the byte array (little-endian).
public func getUInt32() -> UInt32 {
let returnValue = UInt32(_byteArray[_arrayIndex]) |
UInt32(_byteArray[_arrayIndex + 1]) << 8 |
UInt32(_byteArray[_arrayIndex + 2]) << 16 |
UInt32(_byteArray[_arrayIndex + 3]) << 24
_arrayIndex += 4
return returnValue
// Method to decode UTF-8 encoded text data in the byte array.
private func getTextData(_ numberBytes : Int) -> String {
if numberBytes == 0 {
return "" // Tiny optimization?
let startIndex = _arrayIndex
_arrayIndex += numberBytes
return String(bytes: _byteArray[startIndex ..< _arrayIndex], encoding: String.Encoding.utf8)!
}
这是一个更大的类(另请参阅 https://stackoverflow.com/a/41547936/253938 )的摘录,我用它来处理序列化数据。
您需要先将Int8数组转换为数据,然后再转换为字符串。
这是我的解决方案:
var buffer = [Int8](repeating: 0, count: 100)
let data = Data(bytes: buffer as [Int8], count: buffer.count);
return String( data: data, encoding: .utf8)
对于不能将字节数组转换为字符串的任何人,请尝试以下方法
String(data: Data(decrypted), encoding: .utf8)
这是我的字符串扩展示例。我用它来做AES
extension String {
func decryptAES(key: String, iv: String) -> String {
let encrypted = self
let key = Array(key.utf8)
let iv = Array(iv.utf8)
let aes = try AES(key: key, blockMode: CTR(iv: iv), padding: .noPadding)
let decrypted = try aes.decrypt(Array(hex: encrypted))
果断的青椒 · 使用three.js 画渐变的直线_其它_脚本之家 6 月前 |