Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of python's ord(), chr() in go?

Tags:

go

What is the equivalent of python's chr() and ord() functions in golang?

chr(97) = 'a'
ord('a') = 97
like image 632
Salvador Dali Avatar asked Apr 28 '15 08:04

Salvador Dali


People also ask

What is ord () and CHR () in Python?

Python ord() and chr() are built-in functions. They are used to convert a character to an int and vice versa. Python ord() and chr() functions are exactly opposite of each other.

What are the use of Ord () and CHR () function in Python explain with example?

Python ord() example For example, ord('a') returns the integer 97, ord('€') (Euro sign) returns 8364. This is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects. If a Unicode argument is given and Python is built with UCS2 Unicode, then the character's code point must be in the range [0..

What is ord () function in Python?

The ord() function returns the number representing the unicode code of a specified character.

What is CHR ord (' A?

Python chr() and ord() Python's built-in function chr() is used for converting an Integer to a Character, while the function ord() is used to do the reverse, i.e, convert a Character to an Integer.


2 Answers

They are supported as simple conversions:

ch := rune(97)
n := int('a')
fmt.Printf("char: %c\n", ch)
fmt.Printf("code: %d\n", n)

Output (try it on the Go Playground):

char: a
code: 97

Note: you can also convert an integer numeric value to a string which basically interprets the integer value as the UTF-8 encoded value:

s := string(97)
fmt.Printf("text: %s\n", s) // Output: text: a

Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to "\uFFFD".

like image 112
icza Avatar answered Sep 19 '22 18:09

icza


It appears that a simple uint8('a') will produce a correct output. To convert from integer to string string(98) will suffice:

uint8('g') // 103
string(112) // p
like image 30
Salvador Dali Avatar answered Sep 17 '22 18:09

Salvador Dali