如何在Swift中将Int转换为4字节的字节数组? [英] How to convert Int to byte array of 4 bytes in Swift?
问题描述
我正在使用Swift,并尝试将Int(例如:-1133)转换为4个字节的字节数组。我能够将Int转换为8个字节的数组(-1333变为[255、255、255、255、255、255、250、203]),但我需要将其设为4个字节。我知道可以使用其他语言(例如Java)来做到这一点,但是Swift可以解决吗?这是我的代码:(我使用了 THIS 答案)
I'm using Swift and trying to convert an Int (for example: -1333) to a byte array of 4 bytes. I was able to convert an Int to an array of 8 bytes (-1333 becomes [255, 255, 255, 255, 255, 255, 250, 203]), but I need it to be 4 bytes. I know that there are ways to do this in other languages like Java, but is there a way for Swift? Here's my code: (I used THIS answer)
func createByteArray(originalValue: Int)->[UInt8]{
var result:[UInt8]=Array()
var _number:Int = originalValue
let mask_8Bit=0xFF
var c=0
var size: Int = MemoryLayout.size(ofValue: originalValue)
for i in (0..<size).reversed(){
//at: 0 -> insert at the beginning of the array
result.insert(UInt8( _number&mask_8Bit),at:0)
_number >>= 8 //shift 8 times from left to right
}
return result
}
推荐答案
在Java中,整数始终为32位,但在Swift中,可以为32位或64位,具体取决于平台。您的代码在8位字节的64位平台上创建一个与 Int
类型相同的字节数组。
In Java an integer is always 32-bit, but in Swift it can be 32-bit or 64-bit, depending on the platform. Your code creates a byte array with the same size as that of the Int
type, on a 64-bit platform that are 8 bytes.
如果要将转换限制为32位整数,请使用 Int32
代替 Int
,结果将是独立于平台的4字节数组。
If you want to restrict the conversion to 32-bit integers then use Int32
instead of Int
, the result will then be an array of 4 bytes, independent of the platform.
另一种转换方法是
let value: Int32 = -1333
let array = withUnsafeBytes(of: value.bigEndian, Array.init)
print(array) // [255, 255, 250, 203]
或作为通用函数,用于所有大小的整数类型:
Or as a generic function for integer type of all sizes:
func byteArray<T>(from value: T) -> [UInt8] where T: FixedWidthInteger {
withUnsafeBytes(of: value.bigEndian, Array.init)
}
示例:
print(byteArray(from: -1333)) // [255, 255, 255, 255, 255, 255, 250, 203]
print(byteArray(from: Int32(-1333))) // [255, 255, 250, 203]
print(byteArray(from: Int16(-1333))) // [250, 203]
这篇关于如何在Swift中将Int转换为4字节的字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!