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

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

十進位轉二進位(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"


分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.