NSData to [Uint8] in Swift

后端 未结 7 726
无人及你
无人及你 2020-12-04 17:24

I couldn\'t find a solution to this problem in Swift (all of them are Objective-C, and they deal with pointers which I don\'t think exist in Swift in the same form). Is ther

7条回答
  •  有刺的猬
    2020-12-04 17:56

    You can use the getBytes function of NSData to get the byte array equivalent.

    As you did not provide any source code, I will use a Swift String contents that has been converted to NSData.

    var string = "Hello World"
    let data : NSData! = string.dataUsingEncoding(NSUTF8StringEncoding)
    
    let count = data.length / sizeof(UInt8)
    
    // create an array of Uint8
    var array = [UInt8](count: count, repeatedValue: 0)
    
    // copy bytes into array
    data.getBytes(&array, length:count * sizeof(UInt8))
    
    println(array)
    

    Swift 3/4

    let count = data.length / MemoryLayout.size
    
    // create an array of Uint8
    var byteArray = [UInt8](repeating: 0, count: count)
    // copy bytes into array
    data.getBytes(&byteArray, length:count)
    

提交回复
热议问题