How to convert an Int into NSData in Swift?

前端 未结 7 1909
陌清茗
陌清茗 2021-02-03 22:37

In Objective-C I use the following code to

  1. Convert an Int variable into NSData, a packet of bytes.

    int myScore = 0;
    NS         
    
    
            
7条回答
  •  闹比i
    闹比i (楼主)
    2021-02-03 23:03

    Swift 5, add an other option.

    NSData is old, still effective

    Write Data:

    let buffer = NSMutableData()
    let size = MemoryLayout.size
    let big = 1000
    let small = 10
    withUnsafeBytes(of: big, { (p) in
          let bufferPointer = p.bindMemory(to: UInt.self)
          if let address = bufferPointer.baseAddress{
                 buffer.append(address, length: size)
          }
    })
    
    withUnsafeBytes(of: small, { (p) in
          let bufferPointer = p.bindMemory(to: UInt.self)
          if let address = bufferPointer.baseAddress{
               buffer.append(address, length: size)
          }
     })
    

    Read data:

    if let d = buffer.copy() as? Data{
         var big: UInt = 0
         var small: UInt = 0
         let size = MemoryLayout.size
         let meta = NSData(data: data)
         meta.getBytes(&big, range: NSRange(location: 0, length: size))
         meta.getBytes(&small, range: NSRange(location: size, length: size))
    
         print("big:", big, "\nsmall:", small)
        //  big: 1000 
        //  small: 10 
    }
    

    You know the memory layout, the data put in the memory,

    Then put them out exactly.

    unsafe method is funny

提交回复
热议问题