I am writing an application where I need to convert an array of different data types to a data array which I will send to another device through a UDP port.
So far, I have the following code:
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let a: UInt8 = 42
var da:[UInt8] = [a]
let data = Data(buffer: UnsafeBufferPointer(start: &da, count: da.count))
let x = data.toArray(type: UInt8.self)
print(x)
}
}
So far, this works. I get the following output: [42]
If I were to change let a: UInt8 = 42
to let a: Float = 3.14
and var da:[Float] = [a]
, I get the result of [195, 245, 72, 64]
.
All of the above is what I expect. The problem comes in the following code:
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let b: UInt8 = 42
let a: Float = 3.14
var da:[Any] = [a, b]
let data = Data(buffer: UnsafeBufferPointer(start: &da, count: da.count))
let x = data.toArray(type: UInt8.self)
print(x)
}
}
Here, I would expect to get [42, 195, 245, 72, 64]
except I am getting the following result: [42, 0, 0, 0, 0, 0, 0, 0, 176, 10, 10, 0, 0, 96, 0, 0, 104, 41, 172, 143, 255, 127, 0, 0, 32, 161, 114, 0, 1, 0, 0, 0, 195, 245, 72, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 228, 32, 1, 1, 0, 0, 0, 168, 153, 114, 0, 1, 0, 0, 0]
.
Can someone explain to my why this is happening and what I should change to get the expected outcome?
Edit: While I could skip the padding, I am trying to fake a server that is from the below specification while I am developing the app.
https://forums.codemasters.com/discussion/136948/f1-2018-udp-specification#latest