Convert Char to Byte gives wrong result


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

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

The Kotlin behavior is to return the char code.


#2

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


#3

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’


#4

The only way I found to do that is

char.toString().toByte()

#5

You could create an extension

fun Char.parseByte() = this.toString().toByte()

#6
fun Char.parseByte() :Byte {
    if(this !in '0'..'9') throw NumberFormatException(this.toString())
    return (this - '0').toByte()
}