ios 如何在 Swift 中将 Int 转换为 NSData?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28680589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert an Int into NSData in Swift?
提问by Cesare
In Objective-C I use the following code to
在 Objective-C 中,我使用以下代码
Convert an
Int
variable intoNSData
, a packet of bytes.int myScore = 0; NSData *packet = [NSData dataWithBytes:&myScore length:sizeof(myScore)];
Use the converted
NSData
variable into a method.[match sendDataToAllPlayers: packet withDataMode: GKMatchSendDataUnreliable error: &error];
将一个
Int
变量转换为NSData
一个字节包。int myScore = 0; NSData *packet = [NSData dataWithBytes:&myScore length:sizeof(myScore)];
将转换后的
NSData
变量用于方法。[match sendDataToAllPlayers: packet withDataMode: GKMatchSendDataUnreliable error: &error];
I tried converting the Objective-C code into Swift:
我尝试将 Objective-C 代码转换为 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?
但是,我无法将Int
变量转换为 anNSData
并将其用作 a 方法。我怎样才能做到这一点?
回答by Raphael
With Swift 3.x to 5.0:
使用 Swift 3.x 到 5.0:
var myInt = 77
var myIntData = Data(bytes: &myInt,
count: MemoryLayout.size(ofValue: myInt))
回答by Rob
In contemporary versions of Swift, I would do:
在当代版本的 Swift 中,我会这样做:
let score = 1000
let data = withUnsafeBytes(of: score) { Data(e8 03 00 00 00 00 00 00
) }
let value = data.withUnsafeBytes {
let data = withUnsafeBytes(of: score.littleEndian) { Data( e8 03 00 00 00 00 00 00
) }
.load(as: Int.self)
}
And convert that Data
back to an Int
:
并将其转换Data
回一个Int
:
let value = data.withUnsafeBytes {
let data = withUnsafeBytes(of: score.bigEndian) { Data( 00 00 00 00 00 00 03 e8
) }
.load(as: Int.self).littleEndian
}
Note, when dealing with binary representations of numbers, especially when exchanging with some remote service/device, you might want to make the endiannessexplicit, e.g.
请注意,在处理数字的二进制表示时,尤其是在与某些远程服务/设备交换时,您可能希望明确字节顺序,例如
let value = data.withUnsafeBytes {
var myScore: NSInteger = 0
let data = NSData(bytes: &myScore, length: sizeof(NSInteger))
.load(as: Int.self).bigEndian
}
let buffer = NSMutableData()
let size = MemoryLayout<UInt>.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)
}
})
And convert that Data
back to an Int
:
并将其转换Data
回一个Int
:
if let d = buffer.copy() as? Data{
var big: UInt = 0
var small: UInt = 0
let size = MemoryLayout<UInt>.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
}
Versus big endian format, also known as “network byte order”:
与大端格式,也称为“网络字节顺序”:
##代码## ##代码##And convert that Data
back to an Int
:
并将其转换Data
回一个Int
:
Needless to say, if you don't want to worry about endianness, you could use some established standard like JSON (or even XML).
不用说,如果您不想担心字节顺序,您可以使用一些既定的标准,如 JSON(甚至 XML)。
For Swift 2 rendition, see previous revision of this answer.
对于 Swift 2 版本,请参阅此答案的先前修订版。
回答by David V
You can convert in this way:
您可以通过以下方式进行转换:
##代码##回答by dengST30
Swift 5, add an other option.
Swift 5,添加另一个选项。
NSData
is old, still effective
NSData
是旧的,仍然有效
Write Data:
写入数据:
##代码##Read data:
读取数据:
##代码##You know the memory layout, the data put in the memory,
你知道内存布局,放入内存的数据,
Then put them out exactly.
然后把它们准确地放出来。
unsafe
method is funny
unsafe
方法很有趣