Convert Char to Byte gives wrong result

Byte.parseByte("0") // Java: Gives 0

'0'.toByte() // Kotlin: Gives 48

The Kotlin behavior is to return the char code.

“0”.toByte() // Gives 0 as Java

In the first line you parse in the second you cast to byte.

fun main() {
//sampleStart
println("0".toByte())
println('0'.toByte())
//sampleEnd
}
fun main() {
//sampleStart
println('d'.toByte())
println("d".toByte())
//sampleEnd
}

Also 'd'.toByte() works, while "d".toByte() fails with a ‘NumberFormatException’

The only way I found to do that is

char.toString().toByte()

You could create an extension

fun Char.parseByte() = this.toString().toByte()
1 Like
fun Char.parseByte() :Byte {
    if(this !in '0'..'9') throw NumberFormatException(this.toString())
    return (this - '0').toByte()
}
2 Likes