Skip to content

Instantly share code, notes, and snippets.

@mwrites
Last active March 5, 2018 09:07
Show Gist options
  • Save mwrites/44947486eb48e3a0b2cf833079bb2a34 to your computer and use it in GitHub Desktop.
Save mwrites/44947486eb48e3a0b2cf833079bb2a34 to your computer and use it in GitHub Desktop.
Convert Binary, Base X, to Decimal
func baseToDecimal(_ base: Int, notation : [Int]) -> Int {
return notation.reversed().enumerated().filter { $0.element == 1 }.reduce(into: 0) {
let powR = Int(pow(Float(base), Float($1.offset)))
$0 += powR
}
}
func decimal(_ d : Int, toBase base: Int) -> [Int] {
var res = [Int]()
var i = d
while i >= 1 {
let quotient = i / base
let remainder = i % base
if remainder > 0 {
res.append(1)
} else {
res.append(0)
}
i = quotient
}
return res.reversed()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment