Created
August 8, 2017 17:16
-
-
Save pchrysa/e818485051a01c2ad0ab995d2f99c7c3 to your computer and use it in GitHub Desktop.
Convert Decimal to Binary and Vice Versa in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.thecodevs.Converter | |
import com.thecodevs.Math.* | |
fun toDecimal(binaryNumber : String) : Int { | |
var sum = 0 | |
binaryNumber.reversed().forEachIndexed { | |
k, v -> sum += v.toString().toInt() * pow(2, k) | |
} | |
return sum | |
} | |
fun toBinary(decimalNumber: Int, binaryString: String = "") : String { | |
while (decimalNumber > 0) { | |
val temp = "${binaryString}${decimalNumber%2}" | |
return toBinary(decimalNumber/2, temp) | |
} | |
return binaryString.reversed() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.thecodevs.Converter.* | |
fun main(args: Array<String>) { | |
println(toDecimal("10011011")) | |
println(toBinary(155)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.thecodevs.Math | |
import java.lang.Math | |
fun pow(base: Int, exponent: Int) = Math.pow(base.toDouble(), exponent.toDouble()).toInt() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment