How to convert UInt8 byte array to string in Swift

前端 未结 14 2524
野的像风
野的像风 2020-12-05 06:29

I am facing problems while converting UInt8 Byte array to string in swift. I have searched and find a simple solution

String.stringWithBytes(buf         


        
相关标签:
14条回答
  • 2020-12-05 07:00

    You need convert Int8 array to Data firstly, then convert to String.

    This is my solution:

        var buffer = [Int8](repeating: 0, count: 100)
        let data = Data(bytes: buffer as [Int8], count: buffer.count);
        return String( data: data, encoding: .utf8)
    
    0 讨论(0)
  • 2020-12-05 07:05

    Swift 4 / Ubuntu 16.04

    let serverAns = [UInt8](repeating: 0x50, count: 100)
    let readBytes = 8
    let truncatedServerAns = serverAns[0..<readBytes]
    let tsaData = Data(bytes: truncatedServerAns)
    let serverIdStr = String(data: tsaData, encoding: .utf8)
    print("serverIdStr=\(String( describing: serverIdStr))")
    
    // Prints:
    // serverIdStr=Optional("PPPPPPPP")
    
    0 讨论(0)
提交回复
热议问题