How to convert UInt8 byte array to string in Swift

前端 未结 14 2527
野的像风
野的像风 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 06:47

    "MSString(bytes: , length: , encoding: )" does not appear to be working as of July 26th, 2015

    Converting byte values to ASCII seems problematic, if you have hit a wall you can do it the hard way as follows (and maybe I am missing something with swift but I couldn't find any solutions within my timeframe.) This will be done with two functions. The first function accepts a UInt8 and converts that to a "\u{}" representation, which is then returned by the function. Second, another function is set up which takes in a UInt8 array as a parameter, then outputs a string.

    Step #1. Function convert each byte to "\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}"
    

    //.. Add for as many characters as you anticipate...don't forget base 16..

    case 0x09: characterToReturn = "\u{09}"
    case 0x0A: characterToReturn = "\u{0A}"
    
    default: characterToReturn = "\u{0}"
    

    /*.. and all the way up to 0xff */

    case 0xFE: characterToReturn = "\u{FE}"
    case 0xFF: characterToReturn = "\u{FF}"
    
    
    
      }
    

    return characterToReturn

    }

    Step #2 ...Next a function which takes in a UInt8 array as a parameter then returns a string...

    func UInt8ArrayToString(#UInt8Array: [UInt8]) -> String {

    var returnString : String = "" for eachUInt8Byte in UInt8Array {

    returnString += convertToCharacter(UInt8Bits: eachUInt8Byte)

    }

    return returnString }

    This should work in a Swift Playground Make an array

    var myArray : [UInt8] = [0x30, 0x3A, 0x4B]

    //Then apply the functions above

    println(UInt8ArrayToString(UInt8Array: myArray))

提交回复
热议问题