将a强制转换UInt64
为an Int64
是不安全的,因为a UInt64
可以具有大于的数字Int64.max
,这将导致溢出。
以下是将转换UInt64
为Int64
,反之亦然的代码段:
// 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 }
}
}
这只是将二进制数据解释UInt64
为Int64
,即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