Home >Backend Development >Golang >How Do I Convert Between Characters and ASCII Codes in Go?

How Do I Convert Between Characters and ASCII Codes in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 18:31:12645browse

How Do I Convert Between Characters and ASCII Codes in Go?

Go Equivalents of Python's chr() and ord()

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.

chr() Equivalent

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

ord() Equivalent

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.

Additional Conversion Option

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn