In Python, the functions chr() and ord() perform the conversion between characters and their corresponding ASCII codes. In Go, these operations can be achieved through simple conversions.
The chr() function in Python returns the character corresponding to a given ASCII code. In Go, this can be achieved through a type conversion:
ch := rune(97) // rune is an alias for int32 fmt.Printf("char: %c\n", ch) // Output: char: a
The ord() function in Python returns the ASCII code of a given character. In Go, this can be obtained similarly:
n := int('a') fmt.Printf("code: %d\n", n) // Output: code: 97
Note: In Go, characters are represented using UTF-8 encoding, so it's recommended to use the rune type instead of int or byte.
Go also allows converting an integer numeric value to a string, which interprets the integer as a UTF-8 encoded value:
s := string(97) fmt.Printf("text: %s\n", s) // Output: text: a
This provides an alternative way to perform character conversion, but it's typically used when working with strings rather than individual characters.
The above is the detailed content of How Do I Convert Between Characters and ASCII Codes in Go?. For more information, please follow other related articles on the PHP Chinese website!