'convert int to ascii - more than one character in rune literal
How do I convert into to its ASCII?
In java it's System.out.println((char)(49)); //gives 1
I tried
a := '42'
fmt.Println(rune(a))
I get more than one character in rune literal
Solution 1:[1]
The reason you're getting this error is in this variable:
a := '42'
A byte literal may only contain one character, use this instead;
a := byte(42)
Edit:
Use string(a)
to get the expected results, like boo said.
Solution 2:[2]
Use a string conversion to convert an ASCII numeric value to a string containing the ASCII character:
fmt.Println(string(49)) // prints 1
The go vet
command warns about the int
to string
conversion in the this code snippet because the conversion is commonly thought to create a decimal representation of the number. To squelch the warning, use a rune
instead of an int
:
fmt.Println(string(rune(49))) // prints 1
This works for any rune value, not just the ASCII subset of runes.
Another option is to create a slice of bytes with the ASCII value and convert the slice to a string.
b := []byte{49}
fmt.Println(string(b)) // prints 1
A variation on the previous snippet that works on all runes is:
b := []rune{49}
fmt.Println(string(b)) // prints 1
Solution 3:[3]
I suppose to do like this, in a very simple term explaining.
i := 1
fmt.Println("number value", i)
s := strconv.Itoa(i)
fmt.Println("string value", s)
a := []rune(s)[0]
fmt.Println("ascii value", a)
n := string(a)
fmt.Println("back to string value", n)
and output is following:
number value 1
string value 1
ascii value 49
back to string value 1
I know this is not the best one answer, but still it works fine without any issue.
Solution 4:[4]
fmt.Printf("%c", 49)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | ArifMustafa |
Solution 4 | Moacir Schmidt |