美文网首页good
Swift-Byte与Int互转

Swift-Byte与Int互转

作者: SK丿希望 | 来源:发表于2019-05-28 10:52 被阅读0次

    使用案例

        var index = 0
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            index += 150
            let bytes = index.hw_to4Bytes()
            HWPrint(bytes)
            let x = hw_getInt(bytes)
            HWPrint(x)
        }
    
    image.png

    bytes转Int

    func hw_getInt(_ array:[UInt8]) -> Int {
        var value : UInt32 = 0
        let data = NSData(bytes: array, length: array.count)
        data.getBytes(&value, length: array.count)
        value = UInt32(bigEndian: value)
        return Int(value)
    }
    

    Int转bytes

    extension Int {
        // MARK:- 转成 2位byte
        func hw_to2Bytes() -> [UInt8] {
            let UInt = UInt16.init(Double.init(self))
            return [UInt8(truncatingIfNeeded: UInt >> 8),UInt8(truncatingIfNeeded: UInt)]
        }
        // MARK:- 转成 4字节的bytes
        func hw_to4Bytes() -> [UInt8] {
            let UInt = UInt32.init(Double.init(self))
            return [UInt8(truncatingIfNeeded: UInt >> 24),
                    UInt8(truncatingIfNeeded: UInt >> 16),
                    UInt8(truncatingIfNeeded: UInt >> 8),
                    UInt8(truncatingIfNeeded: UInt)]
        }
        // MARK:- 转成 8位 bytes
        func intToEightBytes() -> [UInt8] {
            let UInt = UInt64.init(Double.init(self))
            return [UInt8(truncatingIfNeeded: UInt >> 56),
                UInt8(truncatingIfNeeded: UInt >> 48),
                UInt8(truncatingIfNeeded: UInt >> 40),
                UInt8(truncatingIfNeeded: UInt >> 32),
                UInt8(truncatingIfNeeded: UInt >> 24),
                UInt8(truncatingIfNeeded: UInt >> 16),
                UInt8(truncatingIfNeeded: UInt >> 8),
                UInt8(truncatingIfNeeded: UInt)]
        }
    }
    

    相关文章

      网友评论

        本文标题:Swift-Byte与Int互转

        本文链接:https://www.haomeiwen.com/subject/posrtctx.html