在Swift中将Hexa转换为十进制 [英] Convert Hexa to Decimal in Swift

查看:182
本文介绍了在Swift中将Hexa转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  let h2 =0373
let d4 = Int(h2,基数:16)!
print(d4)// 883

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

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



现在,我正在关注这个



是否有任何其他解决方案可以从Hexa值中减去小数?



任何帮助将不胜感激!

解决方案 16的十六进制表示位符号整数
-120 。您可以先创建一个无符号整数,然后将其转换为具有相同位模式的签名对象:

  let h3 =FF88
让u3 = UInt16(h3,基数:16)! // 65416
let s3 = Int16(bitPattern:u3)// -120


I want to convert Hexa value into decimal. So I have tried this. When value is >0, then it is working fine. But when value is <0, then is returns wrong value.

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

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

When I am passing FF88, then it returns 65416. But actually it is -120.

Right now, I am following this Convert between Decimal, Binary and Hexadecimal in Swift answer. But it didn't works always.

Please check this conversation online. Please see following image for more details of this conversation.

Is there any other solution for get minus decimal from Hexa value.?

Any help would be appreciated !!

解决方案

FF 88 is the hexadecimal representation of the 16-bit signed integer -120. You can create an unsigned integer first and then convert it to the signed counterpart with the same bit pattern:

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

这篇关于在Swift中将Hexa转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆