以 3e4ccccd 轉成 0.2 為範例
Hex2Float(HexStr: "3e4ccccd")
//依據 IEEE 754 https://www.h-schmidt.net/FloatConverter/IEEE754.html,16進位轉Float
func Hex2Float(HexStr:String)
{
let binary = Array(get8Hex2Binary(HexStr:HexStr))
let Sign = binary[0...0]
let Exponent = binary[1...8]
let Mantissa = binary[9...(binary.count-1)]
print("Sign:" + Sign) //0
print("Exponent:" + Exponent) //01111100
print("Mantissa:" + Mantissa) //10011001100110011001101
var s = 1.0
if String(Sign) == "1"
{
s = -1.0
}
let e = Binary2Int(binary: String(Exponent)) - 127
print("e:" + String(e)) //-3
let _2_e = powf(2,Float(e))
print(_2_e) //0.125
let CalcMant = CalculationMantissa(Mantissa: String(Mantissa))
let toFloat = Float(s) * _2_e * CalcMant
print("toFloat:" + String(toFloat)) //0.2
}
//計算Mantissa
func CalculationMantissa(Mantissa:String) -> Float{
var calu_m_sum = 0.0
var e = 0
for m in Mantissa {
//println(char)
e = e - 1
if m == "1"
{
let d = powf(2.0,Float(e))
calu_m_sum = calu_m_sum + Double(d)
}
}
print("calu_m_sum:" + String(1.0 + calu_m_sum)) //1.600000023841858
return Float(1.0 + calu_m_sum)
}
//8個位元字串轉成Binary
func get8Hex2Binary(HexStr:String) -> String{
var binary = String(Int(HexStr, radix: 16)!, radix: 2)
print("binary:" + binary) //111110010011001100110011001101 未補滿
if(binary.count != 32)//要補滿32個位元
{
for index in binary.count..<32 {
binary = "0" + binary
}
}
print("binary:" + binary) //00111110010011001100110011001101 補滿32位元
return binary
}
//Binary轉Int
func Binary2Int(binary:String)->Int
{
let number = Int(binary, radix: 2)
return number!
}
沒有留言:
張貼留言