在Swift 3中将Int附加到数据

时间:2017-03-06 15:41:17

标签: swift datagram

我正在编写数据报,通过UDP套接字将其发送到服务器。如何将Int附加到数据报的末尾(已经组成<div id="scrollable-div" style="margin-bottom: 2rem; height: 150px; border: 1px solid #CCC; overflow: auto;"> <h5 style="color: #666">test12 <span id="display" class="pull-right">50%</span></h5> <div class="progress"> <div data-values="50" class="progress-bar" style="color: rgb(255, 255, 255);"></div> </div> <div style="height: 500px;"><!-- push down to show scroll --></div> </div> <!-- JS code --> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>)?

2 个答案:

答案 0 :(得分:4)

您可以使用

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

Data的方法。您可能还想转换该值 在通信之间进行网络(大端)字节顺序 不同的平台,并使用固定大小的类型,如(U)Int16(U)Int32(U)Int64

示例:

var data = Data()

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

print(data as NSData) // <12345678>

答案 1 :(得分:0)

更好的方法:

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

withUnsafePointer(to: &bigEndianVal) {
    data.append(UnsafeBufferPointer(start: $0, count: 1))
}