bytes转换为字符串swift(或swift2)

时间:2015-11-07 04:25:10

标签: swift swift2

我很快就是新人。我有这个字节:

  

字节:[11,143,102,88,132,238,0,156,100,166,72,98,226,109,51,196,124,124,207,252,204,129, 233,209,112,127,66,177,37,141,169,158,122,74,215,103,13,128,74,81,221,46,219,145,107,131,90, 246,37,212,91,237,32,138,74,147,238,40,182,158,12,124,197,17,92,24,184,44,150,127,147,161, 175,186,227,4,248,44,21,83,0]

我使用了这段代码:

let dencryptedBytes: [UInt8] = try! AES(key: UrlManager.CONNECTION_KEY, iv:UrlManager.CONNECTION_IV, blockMode: .CBC).encrypt(bytes)

结果如下:

  

解码字节:[157,29,111,190,188,31,233,140,​​152,67,196,83,214,238,232,184,101,149,45,184,155,85 ,184,69,155,173,196,145,123,54,238,243,34,178,190,129,106,11,26,147,19,207,204,162,142,81,6 ,24,21,93,80,134,247,151,83,79,214,134,80,222,10,196,64,247,53,194,195,207,230,79,215,134 ,87,32,37,100,82,125,59,41,235,36,144,171,64,247,195,12,115,194,124,243,109,84,44,155] < / p>

但我需要将此字节转换为字符串。我找不到答案。请建议我。 非常感谢!

修改

我发现了这个:

var bytes: [UInt8] = [157, 29, 111, 190, 188, 31, 233, 140, 152, 67, 196, 83, 214, 238, 232, 184, 101, 149, 45, 184, 155, 85, 184, 69, 155, 173, 196, 145, 123, 54, 238, 243, 34, 178, 190, 129, 106, 11, 26, 147, 19, 207, 204, 162, 142, 81, 6, 24, 21, 93, 80, 134, 247, 151, 83, 79, 214, 134, 80, 222, 10, 196, 64, 247, 53, 194, 195, 207, 230, 79, 215, 134, 87, 32, 37, 100, 82, 125, 59, 41, 235, 36, 144, 171, 64, 247, 195, 12, 115, 194, 124, 243, 109, 84, 44, 155]


    print(bytes2String(bytes))

func bytes2String(array:[UInt8]) -> String {
return NSString(data: NSData(bytes: array, length: array.count), encoding: NSUTF8StringEncoding)! as String

}

link:NSData to String in Swift Issues

但它不起作用为什么会这样?

错误:致命错误:在解包可选值时意外发现nil

2 个答案:

答案 0 :(得分:2)

试试这个

(str = String(bytes:d,encoding:NSUTF8StringEncoding))

答案 1 :(得分:1)

如果输入数据不表示utf8编码字符串NSString构造函数失败并返回nil。如果你打开nil值,结果是运行时错误。

NSString(data: NSData(bytes: array, length: array.count), encoding: NSUTF8StringEncoding)!

这意味着,数组bytes: [UInt8]无法表示为uft8字符串。如果我理解,你玩一些加密框架。你确定框架确实正确加密,解密吗?首先做一些测试...