[swift]二、八、十與十六進位(負數)轉換 使用uint16、int16

小黑
發佈於APP
2023/11/08閱讀時間約 4 分鐘

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

let dec = -813
let bin = String(UInt16(bitPattern: Int16(dec)), radix: 2)
print(bin) // "1111110011010011"


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

let dec = -813
let oct = String(UInt16(bitPattern: Int16(dec)), radix: 8)
print(oct) // "176323"


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

let dec = -813
let hex = String(UInt16(bitPattern: Int16(dec)), radix: 16)
print(hex) // "fcd3"


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

let bin = "1111110011010011"
let oct = String( UInt16(bin, radix: 2)!, radix: 8)
print(oct) // "176323"


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

let bin = "1111110011010011"
let dec = Int16(bitPattern: UInt16(bin, radix: 2)!)
print(dec) // -813


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

let bin = "1111110011010011"
let hex = String( UInt16(bin, radix: 2)!, radix: 16)
print(hex) // "fcd3"


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

let oct = "176323"
let bin = String(UInt16(oct, radix: 8)!, radix: 2)
print(bin) // "1111110011010011"


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

let oct = "176323"
let dec = Int16(bitPattern:UInt16(oct, radix: 8)!)
print(dec) // -813


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

let oct = "176323"
let hex = String(UInt16(oct, radix: 8)!, radix: 16)
print(hex) // "fcd3"


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

let hex = "fcd3"
let bin = String(UInt16(hex, radix: 16)!, radix: 2)
print(bin) // "1111110011010011"


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

let hex = "fcd3"
let oct = String(UInt16(hex, radix: 16)!, radix: 8)
print(oct) // "176323"


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

let hex = "fcd3"
let dec = Int16(bitPattern: UInt16(hex, radix: 16)!)
print(dec) // "-813"


7會員
78內容數
嗨,我是一名程式設計師,會在這分享開發與學習紀錄。
留言0
查看全部
發表第一個留言支持創作者!