Thursday, December 13, 2018

Golang Example - Program to Check ASCII Value of a character

 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 which contains 128 characters with integer values from 0 to 127. It can be stored in 8-bit types ie 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.

Example Find ASCII value of a character

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
In the above code, Character is declared and assigned using short assignment operator in charVariable. charVariable type is inferred from right-hand side value. Right-hand side value is a character which is enclosed in single quote. Please note that strings are enclosed in double quotes. To get ASCII value of charVariable, create integer with character assign to integer, and compiler converts the character value to ASCII code. We just converted a variable from one type to other types. This is an example for Converting Character to ASCII 
   Finally Print the character and ASCII code using the Println function

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

ASCII and character are different types, We have to write a casting code. The below program explains about following things convert character 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

Related article


EmoticonEmoticon