How to convert an Int into NSData in Swift?

跟風遠走 提交于 2020-01-01 01:16:07

问题


In Objective-C I use the following code to

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

    int myScore = 0;
    NSData *packet = [NSData dataWithBytes:&myScore length:sizeof(myScore)];
    
  2. Use the converted NSData variable into a method.

    [match sendDataToAllPlayers: 
    packet withDataMode: GKMatchSendDataUnreliable 
    error: &error];
    

I tried converting the Objective-C code into Swift:

var myScore : Int = 0

func sendDataToAllPlayers(packet: Int!,
            withDataMode mode: GKMatchSendDataMode,
            error: NSErrorPointer) -> Bool {

            return true
}

However, I am not able to convert an Int variable into an NSData and use it an a method. How can I do that?


回答1:


With Swift 3.x to 5.0:

var myInt = 77
var myIntData = Data(bytes: &myInt, 
                     count: MemoryLayout.size(ofValue: myInt))



回答2:


In contemporary versions of Swift, I would do:

let score = 1000
let data = withUnsafeBytes(of: score) { Data($0) }
e8 03 00 00 00 00 00 00 

And convert that Data back to an Int:

let value = data.withUnsafeBytes {
    $0.bindMemory(to: Int.self)[0]
}

Note, when dealing with binary representations of numbers, especially when exchanging with some remote service/device, you might want to make the endianness explicit, e.g.

let data = withUnsafeBytes(of: score.littleEndian) { Data($0) }
 e8 03 00 00 00 00 00 00 

And convert that Data back to an Int:

let value = data.withUnsafeBytes {
    $0.bindMemory(to: Int.self)[0].littleEndian
}

Versus big endian format, also known as “network byte order”:

let data = withUnsafeBytes(of: score.bigEndian) { Data($0) }
 00 00 00 00 00 00 03 e8

And convert that Data back to an Int:

let value = data.withUnsafeBytes {
    $0.bindMemory(to: Int.self)[0].bigEndian
}

Needless to say, if you don’t want to worry about endianness, you could use some established standard like JSON (or even XML).


For Swift 2 rendition, see previous revision of this answer.




回答3:


You can convert in this way:

var myScore: NSInteger = 0
let data = NSData(bytes: &myScore, length: sizeof(NSInteger))


来源:https://stackoverflow.com/questions/28680589/how-to-convert-an-int-into-nsdata-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!