简体   繁体   English

Swift 中的 C 样式指针/数组转换?

[英]C-style pointer/array casting in Swift?

Is there any way I can cast an array of different integer sizes to another array type?有什么方法可以将不同整数大小的数组转换为另一种数组类型?

For example, in C, I can do:例如,在 C 中,我可以这样做:

unsigned char byteArray[] = { 0x1, 0x5, 0xF, 0x3, 0xA5, 0x3, 0x8, 0x8, 0xAB };
unsigned long long *largeArray = (unsigned long long *)(byteArray);

which would make largeArray equal to { 0x80803A5030F0501, 0x51B76EB7140024AB } .这将使largeArray等于{ 0x80803A5030F0501, 0x51B76EB7140024AB }

Is there any similar thing in Swift? Swift 中有类似的东西吗? For example, something like:例如,类似于:

let byteArray: [UInt8] = [0x1, 0x5, 0xF, 0x3, 0xA5, 0x3, 0x8, 0x8, 0xAB]
let largeArray = [UInt64](byteArray)

I know it is possible to do programmatically, I was just wondering if there's a built in method before I delve into making my own thing that will cast them.我知道有可能以编程方式进行,我只是想知道在我深入研究制作自己的东西之前是否有内置方法可以投射它们。

Any help will be greatly appreciated!任何帮助将不胜感激!

Let's assume the byteArray had eight bytes in it.假设byteArray有八个字节。 You could do:你可以这样做:

let byteArray: [UInt8] = [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7]

let value = byteArray.withUnsafeBytes { 
    $0.bindMemory(to: UInt64.self)[0].littleEndian    // or .bigEndian
}

Resulting in:导致:

0x0706050403020100     // or 0x0001020304050607 if you use bigEndian

Or, if you had enough bytes for multiple UInt64 , you could do:或者,如果您有足够的字节用于多个UInt64 ,您可以执行以下操作:

let longByteArray: [UInt8] = [
    0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7,
    0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf
]

let values = longByteArray.withUnsafeBytes {
    $0.bindMemory(to: UInt64.self)
}.map {
    $0.littleEndian       // or .bigEndian
}

Resulting in导致

[0x0706050403020100, 0x0f0e0d0c0b0a0908] // or [0x0001020304050607, 0x08090a0b0c0d0e0f] if you use bigEndian

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM