ios - Signed Hex 到 Signed Int Swift

标签 ios iphone swift

我见过很多将 hex 转换为 int 的问题,但这些都是 unsigned-> unsigned 的变体。如何将带符号的十六进制转换为 Int?

例如。

somefunc('0xfffff830')
= -2000

最佳答案

您的问题暗示您正在处理 32 位有符号整数 (否则 0xfffff830 不能被认为是否定的), 所以这会起作用:

let num = "0xfffff830"

let x = Int32(truncatingBitPattern: strtoul(num, nil, 16))
println(x) // -2000

strtoul() 将十六进制字符串转换为无符号整数 UInt,并且 Int32(truncatingBitPattern:) 创建一个(带符号的)32 位整数 从给定参数的最低 32 位开始。


Swift 4 更新:

let num = "0xfffff830"
let x = Int32(bitPattern: UInt32(num.dropFirst(2), radix: 16) ?? 0)
print(x) // -2000

关于ios - Signed Hex 到 Signed Int Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31323924/

相关文章:

ios - Swift 代码组织方式 : Extensions vs. Classes and Structs

iphone - 仅在 shouldChangeCharactersInRange 返回 yes 后调用方法

iPhone - 比较一个 nil NSString 与另一个有值(value)的 NSString 返回 NSOrderedSame

ios - 如何正确获取和设置 UIView 的 UIColor?

objective-c - Swift 有标记指针吗?

ios - 更改自定义单元格内容 View 颜色

ios - 使用 UIAppearance 为 UITableViewCell 文本设置样式

iPhone或 cocoa : Handling order of multiple HTTP requests

iphone - 拍摄完图像后,UIActivityIndi​​catorView没有显示在“相机”叠加 View 上

ios - 在 UIwebView 应用程序中使用 Facebook 登录