0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

16進数を10進数へ変換する計算式

Last updated at Posted at 2017-09-28

16進数を10進数へ変換する計算式

16進数を10進数へ変換する関数などがあり、計算式について考えたことなどなかったが、

今回気になったので、描いてみた。

4E5F <- 左記16進数を変換します。

4×16^3 + E×16^2 + 5×16^1 + F×16^0 = 20063(10進法)

上記のような感じ

これをコードにします。

Swift で書きました。

class HexDecimal {
    
    public func HexDecimal (hex: String) -> Int{
        
        var decimal = 0
        var place = hex.characters.count
        var isNotHex: Bool = false
        for str in hex.characters {
            place -= 1
            let hexStr = self.Hex(hex: String(str), place: place)
            if (hexStr == -1){
                isNotHex = true
                break
            }
            decimal += hexStr
        }
        if (isNotHex == true){
            return -1
        }
        return decimal
    }
    
    
    public func Hex( hex: String, place: Int ) -> Int {
        
        var hexNumber = 1
        
        for _ in 0..<place{
            hexNumber *= 16
        }
        let hexHum = self.HexNumber(hexStr: hex)
        if (hexHum == -1){
            return -1
        }
        return self.HexNumber(hexStr: hex) * hexNumber
    }
    
    public func HexNumber(hexStr: String) -> Int {
        
        switch hexStr {
        case "0":break
        case "1":break
        case "2":break
        case "3":break
        case "4":break
        case "5":break
        case "6":break
        case "7":break
        case "8":break
        case "9":break
        case "A":
            return 10
        case "a":
            return 10
        case "B":
            return 11
        case "b":
            return 11
        case "C":
            return 12
        case "c":
            return 12
        case "D":
            return 13
        case "d":
            return 13
        case "E":
            return 14
        case "e":
            return 14
        case "F":
            return 15
        case "f":
            return 15
        default:
            return -1
        }
        return Int(hexStr)!
    }
}

実行方法

print( ColorUtil().HexDecimal(hex: "4E5F"))

一応エラーハンドリングも書きました。

16進数のみ対応で、対応外の文字が来た場合は-1を返します。

git hub gist:
https://gist.github.com/keisukeYamagishi/a0e87cfa4da899d92ae4dae9ebd77894

気になったので書いてみました

が、

実際はApple が作ったものの使い方を書きに記載しておく

let x = Int("123")
// x == 123

let z = Int("07b", radix: 16) // 16進数変換
print (z) // z == 123 

こちらの方が間違いなく良い、

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?