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

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

问题描述

对于任何(至少是整数)数字来说,是否有任何本地Swift方法来获取其字符串中的十六进制表示?和相反。它不能使用基金会。例如,String类有一个函数

  func toInt() - >诠释? 

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

  let anHex =0xA0
如果让anInt = anHex.toInt(){
println(anInt)//打印128
println(anInt.toHexString())//打印0xA0
}

我知道这不是火箭科学,但如果你想分享它,

PS:这与这个问题类似,区别在于是它与Foundation框架非常相关,而我没有在我的代码中使用它(我也没有导入其他任何东西),现在我想以这种方式保存它,也用于学习目的。

解决方案

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

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

,这样整数
到十六进制字符串和十六进制字符串到整数转换都可以通过内置方法完成
。示例:

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

如果让num2 = Int(str,基数:16){
print(num2)// 1000
}






(旧的回答为Swift 1:)从一个整数到十六进制字符串的转换可以用

  let hex = String(num,radix:16)

(请参阅)。这不需要导入任何Framework
,并且可以使用2到36之间的任何base。



可以完成从十六进制字符串到整数的转换与BSD
库函数 strtoul()(比较
导入达尔文。<如何将二进制转换为十进制在Swift?) / p>

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

 扩展UInt {
$ init(?string:String,radix:UInt){
let digits =0123456789abcdefghijklmnopqrstuvwxyz
var result = UInt(0)
for string.lowercaseString {
如果让range = digits.rangeOfString(String(digit)){
let val = UInt(distance(digits.startIndex,range.startIndex))
如果val> = radix {
返回nil
}
result = result * radix + val
} else {
return nil
}
}
self = result


code


示例:

  let hexString =A0
if let num = UInt(hexString,radix:16){
println(num)
} else {
println(无效输入)
}


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?

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: 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.

解决方案

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
}


(Old answer for Swift 1:) The conversion from an integer to a hex string can be done with

let hex = String(num, radix: 16)

(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.

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.

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
    }
}

Example:

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

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

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