Character codes: Difference between revisions

Content added Content deleted
(CoffeeScript)
(→‎{{header|Go}}: some elaboration)
Line 304: Line 304:
<lang go>fmt.Println('a') // prints "97"
<lang go>fmt.Println('a') // prints "97"
fmt.Println('π') // prints "960"</lang>
fmt.Println('π') // prints "960"</lang>
Go constants are not fully typed however. A character stored in a variable has a data type, and the types most commonly used for character data are <tt>byte,</tt> <tt>rune,</tt> and <tt>string.</tt> This example program shows character codes (as literals) stored in typed variables, and printed out with default formatting. Note that since byte and rune are integer types, the default formatting is a printable base 10 number. String is not numeric, and a little extra work must be done to print the character codes.
<lang go>package main


import "fmt"
To obtain the character code of the first Unicode character in a UTF-8 string:
<lang go>rune, _ := utf8.DecodeRuneInString("π")
fmt.Println(rune) // prints "960"</lang>


func main() {
To print the character represented by a character code, we can create a string of that character (by converting the character code to string, it encodes the character in UTF-8):
// yes, there is more concise syntax, but this makes
// the data types very clear.
var b byte = 'a'
var r rune = 'π'
var s string = "aπ"

fmt.Println(b, r, s)
for _, c := range s { // this gives c the type rune
fmt.Println(c)
}
}</lang>
Output:
<pre>
97 960 aπ
97
960
</pre>

For the second part of the task, printing the character of a given code, the <tt>%c</tt> verb of <tt>fmt.Printf</tt> will do this directly from integer values, emitting the UTF-8 encoding of the code, (which will typically print the character depending on your hardware and operating system configuration.)
<lang go>b := byte(97)
r := rune(960)
fmt.Printf("%c %c\n%c %c\n", 97, 960, b, r)</lang>
outputs
<pre>
a π
a π
</pre>
You can think of the default formatting of strings as being the printable characters of the string. In fact however, it is even simpler. Since we expect our output device to interpret UTF-8, and we expect our string to contain UTF-8, The default formatting simply dumps the bytes of the string to the output.

Examples showing strings constructed from integer constants and then printed:
<lang go>fmt.Println(string(97)) // prints "a"
<lang go>fmt.Println(string(97)) // prints "a"
fmt.Println(string(960)) // prints "π"</lang>
fmt.Println(string(960)) // prints "π"
fmt.Println(string([]rune{97, 960})) // prints ""</lang>


=={{header|Golfscript}}==
=={{header|Golfscript}}==