Swift 本机函数将数字作为十六进制字符串 [英] Swift native functions to have numbers as hex strings

查看:18
本文介绍了Swift 本机函数将数字作为十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于任何(至少是整数)数字,是否有任何原生的 Swift 方法可以在字符串中获取其十六进制表示?而相反.它不能使用 Foundation.例如 String 类有一个函数

Is there any native Swift way for any (at least integer) number to get its hexadecimal representation in a string? And the inverse. It must not use Foundation. For example the String class has a function

func toInt() -> Int?

将表示整数的字符串转换为其 Int 值.我正在寻找类似的东西,使用十六进制字符串.我知道这很容易实现,但如果 Swift 已经有了它会更好.否则,如果您已经对 String 和 Int 进行了扩展以实现以下目标:

which converts a string representing an integer to its Int value. I am looking for something similar, using the hex strings. I know this is easily implementable, but if Swift has it there already it would be better. Otherwise if you made already an extension of String and Int to achieve the following:

let anHex = "0xA0"
if let anInt = anHex.toInt() {
   println(anInt)               // prints 128
   println(anInt.toHexString()) // prints "0xA0"
}

我知道这不是火箭科学,但万一请分享.

I know it isn't rocket science but in case please share it.

PS:这个和这个问题类似,不同的是它和Foundation框架有很大关系,而我没有在我的代码中使用它(我也没有导入其他任何东西),现在我想保持这种方式,也是为了学习目的.

PS: This is similar to this question, the difference is that it was very related to the Foundation framework, while I am not using it in my code (nor I am importing anything else) and for now I'd like to keep it in this way, also for learning purposes.

推荐答案

Swift 2 开始,所有整数类型都有一个构造函数

As of Swift 2, all integer types have a constructor

init?(_ text: String, radix: Int = default)

这样两个整数可以完成到十六进制字符串和十六进制字符串到整数的转换带有内置方法.示例:

so that both integer to hex string and hex string to integer conversions can be done with built-in methods. Example:

let num = 1000
let str = String(num, radix: 16)
print(str) // "3e8"

if let num2 = Int(str, radix: 16) {
    print(num2) // 1000
}

<小时>

(Swift 1 的旧答案:) 可以使用

let hex = String(num, radix: 16)

(参见例如 如何转换小数在 Swift 中将数字转换为二进制?).这不需要导入任何框架并适用于 2 到 36 之间的任何基数.

(see for example How to convert a decimal number to binary in Swift?). This does not require the import of any Framework and works with any base between 2 and 36.

从十六进制字符串到整数的转换可以用 BSD 来完成库函数 strtoul()(比较 如何在 Swift 中将二进制转换为十进制?)如果您愿意import Darwin.

The conversion from a hex string to an integer can be done with the BSD library function strtoul() (compare How to convert a binary to decimal in Swift?) if you are willing to import Darwin.

否则(据我所知)没有内置的 Swift 方法.这是一个扩展根据给定的基数将字符串转换为数字:

Otherwise there is (as far as I know) no built-in Swift method. Here is an extension that converts a string to a number according to a given base:

extension UInt {
    init?(_ string: String, radix: UInt) {
        let digits = "0123456789abcdefghijklmnopqrstuvwxyz"
        var result = UInt(0)
        for digit in string.lowercaseString {
            if let range = digits.rangeOfString(String(digit)) {
                let val = UInt(distance(digits.startIndex, range.startIndex))
                if val >= radix {
                    return nil
                }
                result = result * radix + val
            } else {
                return nil
            }
        }
        self = result
    }
}

示例:

let hexString = "A0"
if let num = UInt(hexString, radix: 16) {
    println(num)
} else {
    println("invalid input")
}

这篇关于Swift 本机函数将数字作为十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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