美文网首页
字节流操作—拼包、拆包

字节流操作—拼包、拆包

作者: Buger123 | 来源:发表于2021-04-29 16:13 被阅读0次

    字节流NSData(OC)、Data(Swift);

    1、不同类型数据拼接字节流(拼包)UInt8、UInt16、UInt32组成的数据流拼接;

    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即为不同类型数据拼接成的字节流;

    2、字节流还原为相应的数据(拆包)

    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

    完成相应解包过程;

    相关文章

      网友评论

          本文标题:字节流操作—拼包、拆包

          本文链接:https://www.haomeiwen.com/subject/wpswrltx.html