2023-11-08|閱讀時間 ‧ 約 4 分鐘

[swift]二、八、十與十六進位轉換

十進位轉二進位(Decimal to Binary)

let dec = 813
let bin = String(dec, radix: 2)
print(bin) // "1100101101"


十進位轉八進位(Decimal to Octal)

let dec = 813
let oct = String(dec, radix: 8)
print(oct) // "1455"


十進位轉十六進位(Decimal to Hexadecimal)

let dec = 813
let hex = String(dec, radix: 16)
print(hex) // "32d"


二進位轉八進位(Binary to Octal)

let bin = "1100101101"
let oct = String(Int(bin, radix: 2)!, radix: 8)
print(oct) // "1455"


二進位轉十進位(Binary to Decimal)

let bin = "1100101101"
let dec = Int(bin, radix: 2)!
print(dec) // 813


二進位轉十六進位(Binary to Hexadecimal)

let bin = "1100101101"
let hex = String(Int(bin, radix: 2)!, radix: 16)
print(hex) // "32d"


八進位轉二進位(Octal to Binary)

let oct = "1455"
let bin = String(Int(oct, radix: 8)!, radix: 2)
print(bin) // "1100101101"


八進位轉十進位(Octal to Decimal)

let oct = "1455"
let dec = Int(oct, radix: 8)!
print(dec) // 813


八進位轉十六進位(Octal to Hexadecimal)

let oct = "1455"
let hex = String(Int(oct, radix: 8)!, radix: 16)
print(hex) // "32d"


十六進位轉二進位(Hexadecimal to Binary)

let hex = "32d"
let bin = String(Int(hex, radix: 16)!, radix: 2)
print(bin) // "1100101101"


十六進位轉八進位(Hexadecimal to Octal)

let hex = "32d"
let oct = String(Int(hex, radix: 16)!, radix: 8)
print(oct) // "1455"


十六進位轉十進位(Hexadecimal to Decimal)

let hex = "32d"
let dec = Int(hex, radix: 16)!
print(dec) // "813"


分享至
成為作者繼續創作的動力吧!
此專題是與APP程式設計相關的內容,包含:原生與跨平台。
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言