您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何将UInt64转换为Int64?

如何将UInt64转换为Int64?

将a强制转换UInt64为an Int64是不安全的,因为a UInt64可以具有大于的数字Int64.max,这将导致溢出。

以下是将转换UInt64Int64,反之亦然的代码段:

// Extension for 64-bit integer signed <-> unsigned conversion

extension Int64 {
    var unsigned: UInt64 {
        let valuePointer = UnsafeMutablePointer<Int64>.allocate(capacity: 1)
        defer {
            valuePointer.deallocate(capacity: 1)
        }

        valuePointer.pointee = self

        return valuePointer.withMemoryRebound(to: UInt64.self, capacity: 1) { $0.pointee }
    }
}

extension UInt64 {
    var signed: Int64 {
        let valuePointer = UnsafeMutablePointer<UInt64>.allocate(capacity: 1)
        defer {
            valuePointer.deallocate(capacity: 1)
        }

        valuePointer.pointee = self

        return valuePointer.withMemoryRebound(to: Int64.self, capacity: 1) { $0.pointee }
    }
}

这只是将二进制数据解释UInt64Int64,即Int64.max,由于64位整数的最高有效位处的符号位,其数字将大于负数。

如果只需要正整数,则 获取绝对值。

根据行为,您可以获取绝对值,或:

if currentValue < 0 {
    return Int64.max + currentValue + 1
} else {
    return currentValue
}

后一种选项类似于剥离符号位。例如:

// Using an 8-bit integer for simplicity

// currentValue
0b1111_1111 // If this is interpreted as Int8, this is -1.

// Strip sign bit
0b0111_1111 // As Int8, this is 127. To get this we can add Int8.max

// Int8.max + currentValue + 1
127 + (-1) + 1 = 127
其他 2022/1/1 18:17:46 有568人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶