How to convert Int to byte array of 4 bytes in Swift?

痞子三分冷 提交于 2019-12-11 06:47:27

问题


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
    }

回答1:


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.

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.

An alternative conversion method is

let value: Int32 = -1333
let array = withUnsafeBytes(of: value.bigEndian) { Array($0) }
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 {
    return withUnsafeBytes(of: value.bigEndian) { Array($0) }
}

Example:

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]


来源:https://stackoverflow.com/questions/56964045/how-to-convert-int-to-byte-array-of-4-bytes-in-swift

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