2017-08-14 183 views
0

我想将十六进制值转换为十进制。所以我试过了。当值大于0时,它工作正常。但是当值为< 0时,则返回错误值。在Swift中将十六进制转换为十进制

let h2 = “0373” 
let d4 = Int(h2, radix: 16)! 
print(d4) // 883 

let h3 = “FF88” 
let d5 = Int(h3, radix: 16)! 
print(d5) // 65416 

当我通过FF88时,它返回65416.但实际上它是-120。

现在,我正在关注此Convert between Decimal, Binary and Hexadecimal in Swift答案。但它并不总是如此。

请检查这个对话online。有关此对话的更多详细信息,请参阅以下图片。

enter image description here

有从十六进制值的获取减​​去十进制任何其他解决方案?

任何帮助将不胜感激!

回答

2

FF 88是签署整数 -12016位的十六进制表示。你可以先创建一个无符号整数,然后 将其转换为签名的副本与同位模式:

let h3 = "FF88" 
let u3 = UInt16(h3, radix: 16)! // 65416 
let s3 = Int16(bitPattern: u3) // -120 
1

十六进制转换取决于整数类型(signed , unsigned),大小(64 bits , 32 bits , 16 bits . .),这是你错过了什么。

源代码:

let h3 = "FF88" 
let d5 = Int16(truncatingBitPattern: strtoul(h3, nil, 16)) 
print(d5) // -120 
相关问题