How to find ASCII Value of a character in Golang

In this example, you will learn below two programs in go language.

  • How to display ASCII value of a character in Go language.
  • Convert/cast Character to/from ASCII in golang

ASCII is a code that contains 128 characters with integer values from 0 to 127. It can be stored in 8-bit types i.e byte In Go languages, There is no character type, but it can be represented in rune data type. Each character contains integer code which is called ASCII code.

How to find the ASCII value of a character in golang?

In the above code,

  • Character is declared and assigned using short assignment operator in charVariable.
  • charVariable type is inferred from the right-hand-side value.
  • Right-hand side value is a character that is enclosed in a single quote. Please note that strings are enclosed in double-quotes.
  • To get ASCII value of charVariable, create integer with character assigned to integer, and compiler converts the character value to ASCII code.
  • We just converted a variable from one type to another type. It is an example for Converting Character to ASCII.
  • Finally, Print the character and ASCII code using the Println function
package main


import (
    "fmt"
)

func main() {
    charVariable: = 'T' // This is infered as rune data type
    asciiCode: = int(charVariable)
    fmt.Printf("%s ASCII code is : %d", string(charVariable), asciiCode)
}

The output of the above program code is as follows.

T ASCII code is: 84

How to Convert/cast ASCII to/from a character in Golang Example?

ASCII and character are different types, We have to write a casting code. The below program explains about following things convert characters to ASCII using int() constructor. Cast ASCII to a character using string() constructor.

package main

import (
    "fmt"
)

func main() {
    // Character to ASCII Code Conversion
    charVariable: = 'T' // This is infered as rune data type
    asciiCode: = int(charVariable)
    fmt.Printf("%s ASCII code is : %d\n", string(charVariable), asciiCode)
    // ASCII Code  to Character  Conversion
    asciiCode1: = 84
    charVariable1: = string(asciiCode1)
    fmt.Printf("%d character is : %s", asciiCode1, charVariable1)

}

When the above code is compiled and executed, the output is

T ASCII code is: 84
84 character is: T

Conclusion

In this program, you learned the following examples

  • How to get the ASCII value of a given character in Go language.
  • How to convert character to/from ASCII in go programming language.