将a强制转换
UInt64为an
Int64是不安全的,因为a
UInt64可以具有大于的数字
Int64.max,这将导致溢出。
以下是将转换
UInt64为
Int64,反之亦然的代码段:
// Extension for 64-bit integer signed <-> unsigned conversionextension 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// currentValue0b1111_1111 // If this is interpreted as Int8, this is -1.// Strip sign bit0b0111_1111 // As Int8, this is 127. To get this we can add Int8.max// Int8.max + currentValue + 1127 + (-1) + 1 = 127



