字節(jié)流NSData(OC)、Data(Swift);
1祖娘、不同類型數(shù)據(jù)拼接字節(jié)流(拼包)UInt8失尖、UInt16啊奄、UInt32組成的數(shù)據(jù)流拼接;
var?ar: [UInt8] = Array.init(repeating: 0, count: 4)
ar[0] = 15
ar[1] = 13
let?aa_ar = Data(bytes: ar, count: ar.count)
var?br: [UInt16] = Array.init(repeating: 0, count: 4)
br[0] = 2
br[1] = 1
br[2] = 21474
br[3] = 235
let?ba_ar = Data(bytes: br, count: br.count * 2)
var?cr: [UInt32] = Array.init(repeating: 0, count: 4)
cr[0] = 3454
let?ca_ar = Data(bytes: cr, count: cr.count * 4)
let?data = aa_ar + ba_ar + ca_ar
print("\(ar)--\(aa_ar)--\(br)--\(ba_ar)--\(ba_ar)--\(cr)--\(ca_ar)--------\(data)")
[15, 13, 0, 0]--4 bytes--[2, 1, 21474, 235]--8 bytes--8 bytes--[3454, 0, 0, 0]--16 bytes--------28 bytes
data即為不同類型數(shù)據(jù)拼接成的字節(jié)流掀潮;
2菇夸、字節(jié)流還原為相應(yīng)的數(shù)據(jù)(拆包)
var?unpackingNum: UInt8 = 0
data[1..<2].withUnsafeBytes { rawBufferPointer?in
if?let?rawPointer = rawBufferPointer.baseAddress {
unpackingNum = rawPointer.load(as: UInt8.self)
}
}
var?unpackingNum1: UInt16 = 0
ba_ar[10..<12].withUnsafeBytes { rawBufferPointer?in
if?let?rawPointer = rawBufferPointer.baseAddress {
unpackingNum1 = rawPointer.load(as: UInt16.self)
}
}
var?unpackingNum2: UInt32 = 0
data[12..<16].withUnsafeBytes { rawBufferPointer?in
if?let?rawPointer = rawBufferPointer.baseAddress {
unpackingNum2 = rawPointer.load(as: UInt32.self)
}
}
print("-----\(unpackingNum)-----\(unpackingNum1) -----\(unpackingNum2)")
-----13-----235 -----3454
完成相應(yīng)解包過程;