如何在Swift中将二进制转换为十进制? [英] How to convert a binary to decimal in Swift?

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

问题描述

我正在寻找一种简单的方法来在Swift中将二进制数转换为十进制数.例如,二进制的"10"变为十进制的"2".

I am looking for a simple way to convert a binary number in decimal in Swift. For example, "10" in binary becomes "2" in decimal.

谢谢

推荐答案

更新 :所有整数类型都有一个

Update for Swift 2: All integer types have an

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

现在

方法,该方法根据以下内容将字符串转换为整数 给定的基数:

method now, which converts a string to an integer according to a given base:

let binary = "11001"
if let number = Int(binary, radix: 2) { 
    print(number) // Output: 25
}


(先前的回答:)您可以简单地使用BSD库函数strtoul(),该函数将字符串转换为 根据给定基数的数字:


(Previous answer:) You can simply use the BSD library function strtoul(), which converts a string to a number according to a given base:

let binary = "11001"
let number = strtoul(binary, nil, 2)
println(number) // Output: 25

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

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