在Swift中转换十进制,二进制和十六进制 [英] Convert between Decimal, Binary and Hexadecimal in Swift
本文介绍了在Swift中转换十进制,二进制和十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 十进制转换为二进制
- 二进制到十进制
- 十进制到十六进制
- 十六进制到十进制二进制到十六进制
- 十六进制到二进制
>
我已经有了一个基本和冗长的方式但我想找出一个非常有效的方法。
对不起,如果问题有点长...
解决方案
Int
具有带有 radix
(base)的构造函数。结合这些,你可以实现所有的转换:
//十进制到二进制
let d1 = 21
让b1 = String(d1,基数:2)
print(b1)//10101
//二进制为十进制
let b2 =10110
让d2 = Int(b2,基数:2)!
print(d2)// 22
//十进制到十六进制
let d3 = 61
let h1 = String(d3,基数:16)
print(h1)//3d
//十六进制到十进制
let h2 =a3
let d4 = Int(h2,基数:16)!
print(d4)// 163
//二进制为十六进制
let b3 =10101011
let h3 = String(Int(b3,radix:2 )!,基数:16)
print(h3)//ab
//十六进制到二进制
let h4 =face
let b4 = String(Int(h4,radix:16)!,radix:2)
print(b4)//1111101011001110
What I want to know is the most code efficient way to convert (in swift 2):
- Decimal to Binary
- Binary to Decimal
- Decimal to Hexadecimal
- Hexadecimal to Decimal
- Binary to Hexadecimal
- Hexadecimal to Binary
I already have a rudimentary and long-winded way of achieving this, but I would like to find out a very efficient way of doing it.
Sorry if the question is a bit long...
解决方案
Both String
and Int
have constructors which take a radix
(base). Combining those, you can achieve all of the conversions:
// Decimal to binary
let d1 = 21
let b1 = String(d1, radix: 2)
print(b1) // "10101"
// Binary to decimal
let b2 = "10110"
let d2 = Int(b2, radix: 2)!
print(d2) // 22
// Decimal to hexadecimal
let d3 = 61
let h1 = String(d3, radix: 16)
print(h1) // "3d"
// Hexadecimal to decimal
let h2 = "a3"
let d4 = Int(h2, radix: 16)!
print(d4) // 163
// Binary to hexadecimal
let b3 = "10101011"
let h3 = String(Int(b3, radix: 2)!, radix: 16)
print(h3) // "ab"
// Hexadecimal to binary
let h4 = "face"
let b4 = String(Int(h4, radix: 16)!, radix: 2)
print(b4) // "1111101011001110"
这篇关于在Swift中转换十进制,二进制和十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文