在 Swift 中进行十进制、二进制和十六进制之间的转换 [英] Convert between Decimal, Binary and Hexadecimal in Swift

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

问题描述

我想知道的是最高效的代码转换方式(在 swift 2 中):

What I want to know is the most code efficient way to convert (in swift 2):

  • 十进制转二进制
  • 二进制转十进制
  • 十进制转十六进制
  • 十六进制转十进制
  • 二进制转十六进制
  • 十六进制转二进制

我已经有了实现这一目标的基本且冗长的方法,但我想找到一种更有效的方法.

I already have a rudimentary and long-winded way of achieving this, but I would like to find a more efficient way.

推荐答案

StringInt 都具有采用 radix(基).结合这些,您可以实现所有转换:

Both String and Int have initializers 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屋!

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