Shankar
Shankar

Reputation: 3088

How to convert char to ascii value in kotlin language

I am developing an android application with kotlin in which I need to convert an string character to its ASCII value,

fun tryDiCript(cypher: String) :String {
        var cypher = "fs2543i435u@$#g#@#sagb@!#12416@@@"
        var originalText = ""

        var regEx =Regex("[a-z]")
        for(char in  regEx.findAll(cypher))
        {                 
            originalText += (char.value.toInt()).toString()            
        }
       return originalText
}

this tutorial website showed me to use char.toInt() but it gives runtime error saying

Caused by: java.lang.NumberFormatException: Invalid int: "u"

so how if anyone knows hot to convert char to ASCII value please help me.

Upvotes: 24

Views: 32808

Answers (4)

Mohamed Keita
Mohamed Keita

Reputation: 191

Since Kotlin 1.5

if your variable is of type char for example 'a' you can simply use a.code.

The old methods (e.g. toByte()) are deprecated now.

Upvotes: 19

BakaWaii
BakaWaii

Reputation: 6992

char.value is a String. When you call String.toInt(), it is expecting a numeric string such as "1", "-123" to be parsed to Int. So, "f".toInt() will give you NumberFormatException since "f" isn't a numeric string.

If you are sure about char.value is a String containing exactly one character only. To get the ascii value of it, you can use:

char.value.first().code

Upvotes: 17

Andy
Andy

Reputation: 128

I checked @ice1000's answer, I found the block below does not work.

fun main(vararg args: String) {
  println('A'.toByte().toInt())
}

As we can see in the Kotlin Documentation String - Kotlin Programming Language,the toByte() function of String "Parses the string as a signed Byte number and returns the result." If the the content of the string is not a number, it will throw a java.lang.NumberFormatException.

But there is another function of String called toByteArray(),this function does no require the content of the string being numbers. My code is as following:

String tempString = "Hello"
val tempArray = tempString.toByteArray()
for (i in tempArray){
    println(i.toInt())
}

Attention that toByteArray() function's definition in kotlin's documentaion:

fun String.toByteArray(
    charset: Charset = Charsets.UTF_8
): ByteArray

The default charset is UTF-8, if you would like to use other charset, you can modify it with the parameter.

Upvotes: 4

ice1000
ice1000

Reputation: 6569

You said ascii, not unicode. So it's easy.

This is an example that shows you how to convert a char ('A') to it's ascii value.

fun main(vararg args: String) {
  println('A'.toByte().toInt())
}

The output is what we expected, 65.

Note this doesn't work with unicode.

Edit 1

I guess this to work.

fun tryDiCript(cypher: String): String {
    var cypher = "fs2543i435u@$#g#@#sagb@!#12416@@@"
    var originalText = ""

    var regEx = Regex("[a-z]")
    for(char in regEx.findAll(cypher))
        originalText += char.value[0].toInt().toString()            
    return originalText
}

And I recommend you to use StringBuilder.

fun tryDiCript(cypher: String): String {
    var cypher = "fs2543i435u@$#g#@#sagb@!#12416@@@"
    val originalText = StringBuilder()

    var regEx = Regex("[a-z]")
    for(char in regEx.findAll(cypher))
        originalText.append(char.value[0].toInt())
    return originalText.toString()
}

Upvotes: 8

Related Questions