6

How can I convert an integer Array to Data?

This is what I have, but I am getting lost in figuring out the final step. I am only interested in the Swift 3 solution.

import Foundation

var buffer = [UInt64]( repeating: 0, count: 1000 )

for x in 0 ..< 1000
{
    buffer[x] = UInt64(x)
}

///////
// What goes here to place buffer into myData

var myData = Data()

//
///////
ericg
  • 7,324
  • 6
  • 39
  • 66
  • 1
    This [answer](https://stackoverflow.com/a/38024025/4763963) may help you. Check the second `extension` in **Generic solution #1**. – Mo Abdul-Hameed Jun 27 '17 at 23:43
  • Your array should be an array of `UInt8`, not `UInt64` if you want each to represent one byte. But then each needs to be in the range 0...255. Or do you want each element of the array to represent 8 bytes? – rmaddy Jun 27 '17 at 23:43
  • 1
    Just a note, you can use one line to initialize your buffer: `let buffer = [UInt64](0..<1000)` –  Jun 28 '17 at 00:12
  • @rmaddy I have the same question as op, but I do need each element of array to represent 8 bytes. Following the the marked answer below, when printing `myData`, length is 32, when it should be 256, right? This might would explain why I dont get the expected value when converting that data to base64 string. what change is necessary? Thanks – AnonProgrammer Oct 01 '20 at 06:57

1 Answers1

6

When you want a Data, better check the initializers of Data.

Data

init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) seems to be useful in your case, as UnsafeBufferPointer can easily made from Array.

var myData = buffer.withUnsafeBufferPointer {Data(buffer: $0)}
print(myData as NSData)
//-> <00000000 00000000 01000000 00000000 02000000 00000000 03000000 00000000 ...

If the result is not what you expect, you need to explain it more.

OOPer
  • 44,179
  • 5
  • 90
  • 123