使用 SWIFT 结构(字节) - 结构到 NSData 和 NSData 到结构 [英] Using Structs (Bytes) with SWIFT - Struct to NSData and NSData to Struct
问题描述
我正在尝试了解结构在 SWIFT 中的工作方式.我熟悉 .NET 如何处理它们以及如何将字节打包成结构等.
I'm trying to understand how structs work within SWIFT. I'm familiar with how .NET handles them and how it packs bytes into a structure, etc.
我发现以下代码有些奇怪:
I'm finding some weirdness with the following code:
struct exampleStruct {
var ModelNumber: Byte!
var MajorVersion: Byte!
var MinorVersion: Byte!
var Revision: Byte!
}
var myStruct = exampleStruct (
ModelNumber: 1,
MajorVersion: 2,
MinorVersion: 3,
Revision: 4
)
myStruct.MinorVersion // << Returns 3
// Struct to NSData.
var data = NSData(
bytes: &myStruct,
length: sizeof(exampleStruct)
)
println("data: \(data)")
println 返回:数据:<01000200 03000400>"
The println returns: "data: <01000200 03000400>"
我期望数据实际上是:数据:<01020304>"
I was expecting the data to actually be: "data: <01020304>"
知道为什么 SWIFT 不将 1 个字节打包为 1 个字节,而是将一个字节打包为 2 个字节(1 个字节为值,1 个字节为 00)?
Any idea why SWIFT is not packing 1 byte as 1 byte, instead it's packing a byte as 2 bytes (1 byte the value and 1 byte as 00)?
另一方面,如果我执行以下操作:
On the flip side if I do the following:
var newStruct = exampleStruct(ModelNumber: nil, MajorVersion: nil, MinorVersion: nil, Revision: nil)
var sendBytes:[Byte] = [0x1, 0x2, 0x3, 0x4]
var newData = NSData(bytes: sendBytes, length: sendBytes.count)
newData.getBytes(
&newStruct,
length: sizeof(exampleStruct)
)
newStruct.MinorVersion // << Returns nil
println(newData)
println(newData) 是正确的,是我期望的值:<01020304>
The println(newData) is correct and what I expect in value: <01020304>
但是,当我访问 minorVersion 时,它返回 nil,而不是我期望的 3.
However, when I access the minorVersion it returns nil, not what I expected as 3.
有没有办法强制结构遵守字节的打包?
Is there a way to force the structure to respect the packing of a byte?
推荐答案
将 Byte!
更改为 Byte
.
否则,您将创建一个包含 Optional
的结构体,它大于一个字节,因为除了保存一个字节之外,它还需要额外的字节来指示它是否为 nil
Otherwise you are creating struct holding Optional<Byte>
which is larger than one byte because in addition to hold a byte, it need extra byte to indicate if it is nil
注意:这可能仍然不起作用,因为您可能需要诸如 __attribute__((packed))
之类的东西来告诉编译器如何处理对齐.AFAIK,它在 Swift 中不可用.
Note: This may still not working as you may need something like __attribute__((packed))
to tell compiler how to deal with alignment. AFAIK, it is not available in Swift.
这篇关于使用 SWIFT 结构(字节) - 结构到 NSData 和 NSData 到结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!