2

I am writing datagram for sending it to a server via UDP socket. How can I append Int to the end of a datagram (already composed Data)?

Kara
  • 6,115
  • 16
  • 50
  • 57
Olex
  • 1,656
  • 3
  • 20
  • 38
  • Where's your code? What have you tried? You'll get more and better answers If you show what you've tried, and demonstrate that you’ve taken the time to try to help yourself. See [Ask] – Ashley Mills Mar 06 '17 at 17:39

2 Answers2

9

You can use the

public mutating func append<SourceType>(_ buffer: UnsafeBufferPointer<SourceType>)

method of Data. You probably also want to convert the value to network (big-endian) byte order when communicating between different platforms, and use fixed-size types like (U)Int16, (U)Int32, or (U)Int64.

Example:

var data = Data()

let value: Int32 = 0x12345678
var beValue = value.bigEndian
data.append(UnsafeBufferPointer(start: &beValue, count: 1))

print(data as NSData) // <12345678>

Update for Swift 4/5:

let value: Int32 = 0x12345678
withUnsafeBytes(of: value.bigEndian) { data.append(contentsOf: $0) }

The intermediate variable is no longer needed.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

Better way to do it:

var data = Data()
     
let value: Int32 = 0x12345678
var bigEndianVal = value.bigEndian

withUnsafePointer(to: &bigEndianVal) {
    data.append(UnsafeBufferPointer(start: $0, count: 1))
}
h345k34cr
  • 3,310
  • 5
  • 21
  • 28