在Swift中转换十进制,二进制和十六进制

编程入门 行业动态 更新时间:2024-10-18 01:42:04
本文介绍了在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中转换十进制,二进制和十六进制

本文发布于:2023-10-24 20:08:08,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   十进制   十六进制

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!