Character codes: Difference between revisions
m
Added Plain English
Not a robot (talk | contribs) (Add CLU) |
m (Added Plain English) |
||
(45 intermediate revisions by 31 users not shown) | |||
Line 1:
[[Category:Basic language learning]]
[[Category:String manipulation]]
[[Category:Simple]]
{{task|Text processing}}
Line 14:
Conversely, given a code, print out the corresponding character.
<br><br>
=={{header|11l}}==
<
print(Char(code' 97)) // prints "a"</
=={{header|360 Assembly}}==
S/360 architecture and EBCDIC was born together.
In EBCDIC, the character 'a' (lowercase letter A) has a code of 129 in decimal and '81'x in hexadecimal.
To perform conversion, we use IC (insert character) and STC (store character) opcodes.
<
CHARCODE CSECT
USING CHARCODE,R13 base register
Line 56 ⟶ 54:
CHAR DS CL1
YREGS
END CHARCODE</
{{out}}
<pre>
Line 66 ⟶ 64:
The printing routine only understands ASCII characters as codes anyway, so the "given a code produce its character" part is trivial.
The <code>PrintChar</code> routine is omitted for brevity. It converts the two cursor variables to a FIX layer address and outputs the character using the NEOGEO's FIX layer (the layer where text is displayed). Characters are stored in ROM and arranged in ASCII order.
<
MOVE.B #'A',D1
Line 139 ⟶ 137:
MOVE.B D1,D0 ;store in low word
popWord D1
rts</
Output can be seen [https://ibb.co/ngtDXpq here.]
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program character64.s */
Line 204 ⟶ 201:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|ABAP}}==
In ABAP you must first cast the character to a byte field and back to a number in order to get its ASCII value.
<
data: c value 'A', n type i.
field-symbols <n> type x.
Line 214 ⟶ 210:
assign c to <n> casting.
move <n> to n.
write: c, '=', n left-justified.</
{{Out}}<pre>A = 65</pre>
=={{header|ACL2}}==
Similar to Common Lisp:
<
(cw "~x0" (code-char 97))</
=={{header|Action!}}==
<
CHAR c=['a]
BYTE b=[97]
Line 229 ⟶ 223:
Put(c) Put('=) PrintBE(c)
PrintB(b) Put('=) Put(b)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Character_codes.png Screenshot from Atari 8-bit computer]
Line 236 ⟶ 230:
97=a
</pre>
=={{header|ActionScript}}==
In ActionScript, you cannot take the character code of a character directly. Instead you must create a string and call charCodeAt with the character's position in the string as a parameter.
<
trace("a".charCodeAt(0));//prints '97'</
=={{header|Ada}}==
<
procedure Char_Code is
begin
Put_Line (Character'Val (97) & " =" & Integer'Image (Character'Pos ('a')));
end Char_Code;</
The predefined language attributes S'Pos and S'Val for every discrete subtype, and Character is such a type, yield the position of a value and value by its position correspondingly.
{{out}}
<pre>a = 97</pre>
=={{header|Aime}}==
<
o_integer('a');
o_byte('\n');
# prints "a"
o_byte(97);
o_byte('\n');</
=={{header|ALGOL 68}}==
In ALGOL 68 the '''format''' $g$ is type aware, hence the type conversion operators '''abs''' & '''repr''' are used to set the type.
<
printf(($gl$, ABS "a")); # for ASCII this prints "+97" EBCDIC prints "+129" #
printf(($gl$, REPR 97)) # for ASCII this prints "a"; EBCDIC prints "/" #
)</
''Character conversions'' may be available in the ''standard prelude'' so that when
a foreign tape is mounted, the characters will be converted transparently as the tape's
records are read.
<
INT errno = open(tape, "/dev/tape1", stand out channel)
make conv(tape, ebcdic conv);
FOR record DO getf(tape, ( ~ )) OD; ~ # etc ... #</
Every '''channel''' has an associated standard character conversion that can be determined
using the ''stand conv'' query routine and then the conversion applied to a particular
file/tape. eg.
<
=={{header|ALGOL W}}==
<
% display the character code of "a" (97 in ASCII) %
write( decode( "a" ) );
% display the character corresponding to 97 ("a" in ASCII) %
write( code( 97 ) );
end.</
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|GNU APL}}
In GNU APL and Dyalog, <tt>⎕UCS</tt> with an integer returns the corresponding Unicode character:
<syntaxhighlight lang="apl"> ⎕UCS 97
a</syntaxhighlight>
and <tt>⎕UCS</tt> with a character returns the corresponding code:
<
97</
Like most things in APL, <tt>⎕UCS</tt> can also be used with an array or with a string (which is an array of characters):
<
APL
⎕UCS 'Hello, world!'
72 101 108 108 111 44 32 119 111 114 108 100 33</
=={{header|AppleScript}}==
<
log(id of "aA")</
{{out}}
<pre>(*97*)
Line 310 ⟶ 298:
The converse instruction is <tt>character id</tt> — or either of its synonyms <tt>string id</tt> and <tt>Unicode text id</tt>. Because of a bug admitted to in Apple's AppleScript Language Guide, the expression <tt>text id</tt>, which one might expect to work, can't be used.
<
--> "a"
Line 320 ⟶ 308:
Unicode text id {72, 101, 108, 108, 111, 33}
--> "Hello!"</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program character.s */
Line 451 ⟶ 438:
</syntaxhighlight>
=={{header|Arturo}}==
<
print to :integer `a`
print to :char 97</
{{out}}
Line 464 ⟶ 450:
97
a</pre>
=={{header|AutoHotkey}}==
<
MsgBox % Asc("a")</
=={{header|AWK}}==
AWK has no built-in way to convert a character into ASCII (or whatever) code;
but a function that does so can be easily built using an associative array (where the keys are the characters).
The opposite can be done using <tt>printf</tt> (or <tt>sprintf</tt>) with <tt>%c</tt>
<
{
return chmap[c]
Line 485 ⟶ 469:
s = sprintf("%c%c", 97, 98)
print s
}</
=={{header|Axe}}==
<
Disp 97▶Char,i</
=={{header|Babel}}==
<
{%d nl <<} eachar</
{{Out}}<pre>
Line 506 ⟶ 488:
</pre>
<
</syntaxhighlight>
{{out}}
babel
=={{header|BASIC}}==
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<
char = "a"
PRINT CHR$(charCode) 'prints a
PRINT ASC(char) 'prints 97</
On the ZX Spectrum string variable names must be a single letter but numeric variables can be multiple characters:
{{works with|ZX Spectrum Basic}}
<
20 LET d$ = "b": REM d$ holds the character
30 PRINT CHR$(c): REM this prints a
40 PRINT CODE(d$): REM this prints 98</
==={{header|Applesoft BASIC}}===
CHR$(97) is used in place of "a" because on the older model Apple II, lower case is difficult to input.
<
{{Out}}<pre>a=97</pre>
Line 534 ⟶ 516:
==={{header|BaCon}}===
<
c$ = "$"
PRINT c$, ": ", ASC(c$)
Line 540 ⟶ 522:
' UTF-8
uc$ = "€"
PRINT uc$, ": ", UCS(uc$), ", ", UCS(c$)</
{{out}}
Line 547 ⟶ 529:
€: 8364, 36</pre>
==={{header|
<syntaxhighlight lang="qbasic">10 print "a - > ";asc("a")
20 print "98 -> ";chr$(98)</syntaxhighlight>
==={{header|Commodore BASIC}}===
Commodore BASIC uses PETSCII code for its character set.
<
20 D$ = "B": REM D$ HOLDS THE CHARACTER 'B'
30 PRINT CHR$(CH): REM THIS PRINTS 'A'
40 PRINT ASC(D$): REM THIS PRINTS 66</
{{Out}}<pre>A
66</pre>
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
<syntaxhighlight lang="qbasic">10 PRINT "a - > "; ASC("a")
20 PRINT "98 -> "; CHR$(98)</syntaxhighlight>
==={{header|IS-BASIC}}===
<
110 PRINT CHR$(65)</
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">10 PRINT "a - > "; ASC("a")
20 PRINT "98 -> "; CHR$(98)</syntaxhighlight>
==={{header|QBasic}}===
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|FreeBASIC}}
{{works with|GW-BASIC}}
{{works with|MSX BASIC}}
{{works with|PC-BASIC}}
{{works with|Run BASIC}}
{{works with|Yabasic}}
<syntaxhighlight lang="qbasic">PRINT "a - > "; ASC("a")
PRINT "98 -> "; CHR$(98)</syntaxhighlight>
==={{header|Sinclair ZX81 BASIC}}===
<syntaxhighlight lang="basic">10 REM THE ZX81 USES ITS OWN NON-ASCII CHARACTER SET
20 REM WHICH DOES NOT INCLUDE LOWER-CASE LETTERS
30 PRINT CODE "A"
40 PRINT CHR$ 38</syntaxhighlight>
{{out}}
<pre>38
A</pre>
==={{header|SmallBASIC}}===
<syntaxhighlight lang="qbasic">
Print "a -> "; Asc("a")
Print "98 -> "; Chr(98)
</syntaxhighlight>
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">PRINT "a - > "; ord("a")
PRINT "98 -> "; chr$(98)
END</syntaxhighlight>
==={{header|XBasic}}===
{{works with|Windows XBasic}}
{{works with|Linux XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Character codes"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
PRINT "a - >"; ASC("a")
PRINT "98 -> "; CHR$(98)
END FUNCTION
END PROGRAM</syntaxhighlight>
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">print "a - > ", asc("a")
print "98 -> ", chr$(98)</syntaxhighlight>
=={{header|BASIC256}}==
<syntaxhighlight lang="freebasic"># ASCII char
charCode = 97
char$ = "a"
print chr(97) #prints a
print asc("a") #prints 97
# Unicode char
charCode = 960
char$ = "π"
print chr(960) #prints π
print asc("π") #prints 960</syntaxhighlight>
{{out}}
<pre>a
97
π
960</pre>
=={{header|Batch File}}==
<
@echo off
Line 604 ⟶ 658:
echo %=exitcodeAscii%
exit /b
</syntaxhighlight>
{{in}}
<pre>
Line 615 ⟶ 669:
a
</pre>
=={{header|BBC BASIC}}==
<
char$ = "a"
PRINT CHR$(charCode) : REM prints a
PRINT ASC(char$) : REM prints 97</
=={{header|Befunge}}==
The instruction <tt>.</tt> will output as an integer. <tt>,</tt> will output as ASCII character.
<
=={{header|BQN}}==
BQN's character arithmetic makes it easy to convert between numbers and characters. Since arithmetic generalizes to arrays, the same function works for both integers and arrays. Here, only the conversion from number to character is defined, since it can be automatically inverted with Undo (<code>⁼</code>): the inverse simply subtracts <code>@</code>.
<syntaxhighlight lang="bqn"> FromCharCode ← @⊸+
@⊸+
FromCharCode 97
'a'
FromCharCode 97‿67‿126
"aC~"
FromCharCode⁼ 'a'
97</syntaxhighlight>
=={{header|Bracmat}}==
<
$ ( str
$ ( "\nLatin a
Line 647 ⟶ 709:
)
)
)</
{{Out}}<pre>Latin a
ISO-9959-1: 97 = a
UTF-8: 97 = a
Cyrillic а (UTF-8): 1072 = а</pre>
=={{header|C}}==
<tt>char</tt> is already an integer type in C, and it gets automatically promoted to <tt>int</tt>. So you can use a character where you would otherwise use an integer. Conversely, you can use an integer where you would normally use a character, except you may need to cast it, as <tt>char</tt> is smaller.
<
int main() {
Line 662 ⟶ 723:
printf("%c\n", 97); /* prints "a"; we don't have to cast because printf is type agnostic */
return 0;
}</
=={{header|C sharp|C#}}==
C# represents strings and characters internally as Unicode,
so casting a char to an int returns its Unicode character encoding.
<
namespace RosettaCode.CharacterCode
Line 679 ⟶ 739:
}
}
}</
=={{header|C++}}==
<tt>char</tt> is already an integer type in C++, and it gets automatically promoted to <tt>int</tt>. So you can use a character where you would otherwise use an integer. Conversely, you can use an integer where you would normally use a character, except you may need to cast it, as <tt>char</tt> is smaller.
In this case, the output operator <tt><<</tt> is overloaded to handle integer (outputs the decimal representation) and character (outputs just the character) types differently, so we need to cast it in both cases.
<
int main() {
Line 691 ⟶ 750:
std::cout << (char)97 << std::endl; // prints "a"
return 0;
}</
=={{header|Clojure}}==
<
(print (char 97)) ; prints \a
Line 703 ⟶ 761:
; use String because char in Java can't represent characters outside Basic Multilingual Plane
(print (.codePointAt "𝅘𝅥𝅮" 0)) ; prints 119136
(print (String. (int-array 1 119136) 0 1)) ; prints 𝅘𝅥𝅮</
=={{header|CLU}}==
<
po: stream := stream$primary_output()
Line 716 ⟶ 773:
% To turn an integer into a character code, use char$i2c
stream$putc(po, char$i2c( 97 ) ); % prints 'a'
end start_up</
{{out}}
<pre>97
a</pre>
=={{header|COBOL}}==
Tested with GnuCOBOL on an ASCII based GNU/Linux system.
Running this code on EBCDIC native hardware would display a control code and 000000093.
<
program-id. character-codes.
remarks. COBOL is an ordinal language, first is 1.
Line 732 ⟶ 788:
display function ord('*')
goback.
end program character-codes.</
{{out}}
Line 738 ⟶ 794:
)
000000043</pre>
=={{header|CoffeeScript}}==
CoffeeScript transcompiles to JavaScript, so it uses the JS standard library.
<
console.log String.fromCharCode 97 # a</
=={{header|Common Lisp}}==
<
(princ (code-char 97)) ; prints "a"</
=={{header|Component Pascal}}==
BlackBox Component Builder
<
VAR
c : CHAR;
Line 758 ⟶ 811:
c := CHR(3A9H);
StdLog.Char(c);StdLog.String(":> ");StdLog.Int(ORD(c));StdLog.Ln
END CharCodes;</
{{Out}}
<pre>A:> 65
Ω:> 937</pre>
=={{header|D}}==
<
import std.stdio, std.utf;
Line 775 ⟶ 827:
// 'index' has moved to next character input position.
assert(index == 1);
}</
{{out}}
<pre>97</pre>
=={{header|Dc}}==
A dc program cannot look into strings. But it can convert numeric values into single char strings or print numeric codes directly:
<syntaxhighlight lang
{{out}}
<pre>a</pre>
=={{header|Delphi}}==
Example from Studio 2006.
<
{$APPTYPE CONSOLE}
Line 805 ⟶ 855:
Readln;
end.</
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc nonrec main() void:
writeln(pretend(97, char)); /* prints "a" */
writeln(pretend('a', byte)); /* prints 97 */
corp</syntaxhighlight>
=={{header|DWScript}}==
<
PrintLn(Chr(97));</
=={{header|Dyalect}}==
<syntaxhighlight lang="dyalect">print('a'.Order())
print(Char(97))</syntaxhighlight>
=={{header|E}}==
<
# value: 97
? <import:java.lang.makeCharacter>.asChar(97)
# value: 'a'</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">print
print
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module CharacterCodes {
@Inject Console console;
void run() {
for (Char char : ['\0', '\d', 'A', '$', '¢', '~', '˜']) {
// character to its integer value
UInt32 codepoint = char.codepoint;
// integer value back to its character value
Char fromCodePoint = codepoint.toChar(); // or: "new Char(codepoint)"
console.print($|Character {char.quoted()}:\
| Unicode codepoint={char.codepoint},\
| ASCII={char.ascii},\
| UTF8 bytes={char.utf8()},\
| char from codepoint={fromCodePoint.quoted()}
);
}
}
}
</syntaxhighlight>
{{out}}
<pre>
Character '\0': Unicode codepoint=0, ASCII=True, UTF8 bytes=0x00, char from codepoint='\0'
Character '\d': Unicode codepoint=127, ASCII=True, UTF8 bytes=0x7F, char from codepoint='\d'
Character 'A': Unicode codepoint=65, ASCII=True, UTF8 bytes=0x41, char from codepoint='A'
Character '$': Unicode codepoint=36, ASCII=True, UTF8 bytes=0x24, char from codepoint='$'
Character '¢': Unicode codepoint=162, ASCII=False, UTF8 bytes=0xC2A2, char from codepoint='¢'
Character '~': Unicode codepoint=126, ASCII=True, UTF8 bytes=0x7E, char from codepoint='~'
Character '˜': Unicode codepoint=732, ASCII=False, UTF8 bytes=0xCB9C, char from codepoint='˜'
</pre>
=={{header|Eiffel}}==
All characters are of the type CHARACTER_8 (ASCII encoding) or CHARACTER_32 (Unicode encoding). CHARACTER is a synonym for either of these two (depending on the compiler option). Characters can be assigned using character literals (a single character enclosed in single quotes) or code value notation (of the form '%/value/' where value is an integer literal of any of the recognized forms).
<
class
APPLICATION
Line 853 ⟶ 944:
end
end
</syntaxhighlight>
Limitations: There is no "put_character_32" feature for standard io (FILE class), so there appears to be no way to print Unicode characters.
=={{header|Elena}}==
ELENA
<
public program()
Line 865 ⟶ 955:
var ch := $97;
console.printLine
console.printLine(ch.toInt())
}</
{{out}}
<pre>
Line 876 ⟶ 966:
=={{header|Elixir}}==
A String in Elixir is a UTF-8 encoded binary.
<
97
iex(2)> to_string([code])
"a"</
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(string-to-char "a") ;=> 97
(format "%c" 97) ;=> "a"</syntaxhighlight>
=={{header|EMal}}==
<syntaxhighlight lang="emal">
^|ord and chr work with Unicode code points|^
writeLine(ord("a")) # prints "97"
writeLine(chr(97)) # prints "a"
writeLine(ord("π")) # prints "960"
writeLine(chr(960)) # prints "π"
writeLine()
var cps = int[]
for each var c in text["a", "π", "字", "🐘"]
var cp = ord(c)
cps.append(cp)
writeLine(c + " = " + cp)
end
writeLine()
for each int i in cps
var c = chr(i)
writeLine(i + " = " + c)
end
</syntaxhighlight>
{{out}}
<pre>
97
a
960
π
a = 97
π = 960
字 = 23383
🐘 = 128024
97 = a
960 = π
23383 = 字
128024 = 🐘
</pre>
=={{header|Erlang}}==
In Erlang, lists and strings are the same, only the representation changes. Thus:
<
#Fun<erl_eval.6.13229925>
2> F("a").
97</
If entered manually, one can also get ASCII codes by prefixing characters with <tt>$</tt>:
<
97</
Unicode is fully supported since release R13A only.
=={{header|Euphoria}}==
<
printf(1,"%s\n", 97) -- prints "a"</
=={{header|F Sharp|F#}}==
<
let n = 65
printfn "%d" (int c)
printfn "%c" (char n)</
{{Out}}<pre>65
A</pre>
=={{header|Factor}}==
<
"ア" first .
12450 1string print</
=={{header|FALSE}}==
<
"65,</
=={{header|Fantom}}==
A character is represented in single quotes: the 'toInt' method returns the code for the character. The 'toChar' method converts an integer into its respective character.
<
a
fansh> 'a'.toInt
97</
=={{header|Fennel}}==
<syntaxhighlight lang="fennel">
(string.byte :A) ; 65
(string.char 65) ; "A"
</syntaxhighlight>
=={{header|Forth}}==
As with C, characters are just integers on the stack which are treated as ASCII.
<
dup . \ 97
emit \ a</
=={{header|Fortran}}==
Functions ACHAR and IACHAR specifically work with the ASCII character set, while the results of CHAR and ICHAR will depend on the default character set being used.
<
WRITE(*,*) CHAR(97), ICHAR("a")</
=={{header|Free Pascal}}==
''See [[#Pascal|Pascal]]''
=={{header|FreeBASIC}}==
<
' FreeBASIC v1.05.0 win64
Print "a - > "; Asc("a")
Line 950 ⟶ 1,073:
Sleep
End
</syntaxhighlight>
{{out}}
Line 957 ⟶ 1,080:
98 -> b
</pre>
=={{header|Frink}}==
The function <code>char[x]</code> in Frink returns the numerical Unicode codepoints for a string or character, or returns the Unicode string for an integer value or array of integer values. The <code>chars[x]</code> returns an array even if the string is a single character. These functions also correctly handle upper-plane Unicode characters as a single codepoint.
<
println[chars["a"]] // prints [97] (an array)
println[char[97]] // prints a
println[char["Frink rules!"]] // prints [70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33]
println[[70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33]] // prints "Frink rules!"</
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
print "a -> "; ASC("a")
print "98 -> "; CHR$(98)
handleevents
</syntaxhighlight>
{{output}}
<pre>
a -> 97
98 -> b
</pre>
=={{header|Gambas}}==
<
Dim sChar As String
Line 976 ⟶ 1,113:
Print "ASCII code " & sChar & " represents " & Chr(Val(sChar))
End</
Output:
<pre>
Line 983 ⟶ 1,120:
</pre>
{{header|GAP}}==
<syntaxhighlight lang="gap"># Code must be in 0 .. 255.
CharInt(65);
# 'A'
IntChar('Z');
# 90</
=={{header|Go}}==
In Go, a character literal ''is'' simply an integer constant of the character code:
<
fmt.Println('π') // prints "960"</
<
import (
Line 1,005 ⟶ 1,144:
// Given a code, print out the corresponding character.
fmt.Printf("%c\n", 65) // prt A
}</
Literal constants in Go are not typed (named constants can be).
The variable and constant types most commonly used for character data are <code>byte</code>, <code>rune</code>, and <code>string</code>.
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.
<
import "fmt"
Line 1,029 ⟶ 1,168:
// We can also print the bytes of a string without an explicit loop
fmt.Printf("\n string bytes: % #x\n", s)
}</
{{out}}
<pre>
Line 1,038 ⟶ 1,177:
</pre>
For the second part of the task, printing the character of a given code, the <code>%c</code> verb of <code>fmt.Printf</code> 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).
<
r := rune(960)
fmt.Printf("%c %c\n%c %c\n", 97, 960, b, r)</
{{out}}
<pre>
Line 1,049 ⟶ 1,188:
Examples showing strings constructed from integer constants and then printed:
<
fmt.Println(string(960)) // prints "π"
fmt.Println(string([]rune{97, 960})) // prints "aπ"</
=={{header|Golfscript}}==
To convert a number to a string, we use the array to string coercion.
<syntaxhighlight lang
To convert a string to a number, we have a many options, of which the simplest and shortest are:
<
'a'(\;p
'a'0=p
'a'{}/p</
=={{header|Groovy}}==
Groovy does not have a character literal at all, so one-character strings have to be ''coerced'' to '''char'''. Groovy '''printf''' (like Java, but unlike C) is ''not type-agnostic'', so the cast or coercion from '''char''' to '''int''' is also required. The reverse direction is considerably simpler.
<
printf ("%c\n", 97)</
{{Out}}
<pre>97
a</pre>
=={{header|Haskell}}==
<
main = do
Line 1,077 ⟶ 1,213:
print (chr 97) -- prints "'a'"
print (ord 'π') -- prints "960"
print (chr 960) -- prints "'\960'"</
=={{header|HicEst}}==
<
=={{header|HolyC}}==
<
Print("%c\n", 97); /* prints "a" */</
=={{header|Hoon}}==
<
++ enc
|= char=@t `@ud`char
++ dec
|= code=@ud `@t`code
--</
=={{header|i}}==
<
print(number('a'))
print(text([97]))
}</
=={{header|Icon}} and {{header|Unicon}}==
<
if *arglist > 0 then L := arglist else L := [97, "a"]
every x := !L do
write(x, " ==> ", char(integer(x)) | ord(x) ) # char produces a character, ord produces a number
end</
Icon and Unicon do not currently support double byte character sets.
{{Out}}<pre>97 ==> a
a ==> 97</pre>
=={{header|Io}}==
Here character is a sequence (string) of length one.
<
97 asCharacter println // --> a
"π" at(0) println // --> 960
960 asCharacter println // --> π</
=={{header|J}}==
<
abc☺
3 u: 7 u: 'abc☺'
97 98 99 9786</
<code>7 u:</code> converts
<
97 98 99 226 152 186</
Also, if we limit ourselves to ascii, we have other ways of accomplishing the same thing. <code>a.</code> is a list of the 8 bit character codes and we can index from it, or search it (though that's mostly a notational convenience, since the underlying type already gives us all we need to know).
<
abc
a.i.'abc'
97 98 99</
=={{header|Java}}==
In Java, a <code>char</code> is a 2-byte unsigned value, so it will fit within an 4-byte <code>int</code>.<br />
<br />
To convert a character to it's ASCII code, cast the <code>char</code> to an <code>int</code>.<br />
The following will yield <kbd>97</kbd>.
<syntaxhighlight lang="java">
(int) 'a'
</syntaxhighlight>
You could also specify a unicode hexadecimal value, using the <kbd>\u</kbd> escape sequence.
<syntaxhighlight lang="java">
(int) '\u0061'
</syntaxhighlight>
To convert an ASCII code to it's ASCII representation, cast the <code>int</code> value to a <code>char</code>.
<syntaxhighlight lang="java">
(char) 97
</syntaxhighlight>
Java also offers the <code>Character</code> class, comprised of several utilities for Unicode based operations.<br />
Here are a few examples.<br /><br />
Get the integer value represented by the ASCII character.<br />
The second parameter here, is the radix.
This will return an <code>int</code> with the value of <kbd>1</kbd>.
<syntaxhighlight lang="java">
Character.digit('1', 10)
</syntaxhighlight>
Inversely, get the ASCII representation of the integer.<br />
Again, the second parameter is the radix.
This will return a <code>char</code> with the value of '<kbd>1</kbd>'.
<syntaxhighlight lang="java">
Character.forDigit(1, 10)
</syntaxhighlight>
=={{header|JavaScript}}==
Here character is just a string of length 1
<
console.log(String.fromCharCode(97)); // prints "a"</
ES6 brings '''String.codePointAt()''' and '''String.fromCodePoint()''', which provide access to 4-byte unicode characters,
in addition to the usual 2-byte unicode characters.
<
{{Out}}
<syntaxhighlight lang
and
<
return String.fromCodePoint(x);
})</
{{Out}}
<
=={{header|Joy}}==
<
97 chr.</
=={{header|jq}}==
jq data strings are JSON strings, which can be "explode"d into an array of integers, each representing a Unicode codepoint. The inverse of the <tt>explode</tt> filter is <tt>implode</tt>. <tt>explode</tt> can of course be used for single-character strings, and so for example:
<
[97] | implode # => "a"</
Here is a filter which can be used to convert an integer to the corresponding
character:<
</syntaxhighlight>
Example:
1024 | chr # => "Ѐ"
=={{header|Julia}}==
Julia character constants (of type <code>Char</code>) are treated as an integer type representing the Unicode codepoint of the character, and can easily be converted to and from other integer types.
<
println(Char(97))</
{{out}}<pre>97
a</pre>
=={{header|K}}==
<
97 98 99 65 66 67
_ci 97 98 99 65 66 67
"abcABC"</
=={{header|Kotlin}}==
<syntaxhighlight lang
var c = 'a'
var i = c.
println("$c <-> $i")
i += 2
c = i.toChar()
println("$i <-> $c")
}</
{{out}}
Line 1,229 ⟶ 1,367:
{{VI snippet}}<br/>
[[File:LabVIEW_Character_codes.png]]
=={{header|Lang}}==
{{trans|Python}}
<syntaxhighlight lang="lang">
fn.println(fn.toValue(a)) # Prints "97"
fn.println(fn.toChar(97)) # Prints "a"
# Unicode
fn.println(fn.toValue(π)) # Prints "960"
fn.println(fn.toChar(960)) # Prints "π"
</syntaxhighlight>
=={{header|Lang5}}==
<
'\\ comb -1 remove append "]^_`abcdefghijklmnopqrstuvwxyz{|}~" comb append ;
: CODE 95 iota 33 + ; : comb "" split ;
Line 1,239 ⟶ 1,388:
'a ord . # 97
97 chr . # a</
=={{header|langur}}==
Langur has code point literals (enclosed in straight single quotes), which may use escape codes. They are integers.
The s2cp(), cp2s(), and
<
val .a2 = 97
val .a3 = "a"[1]
Line 1,256 ⟶ 1,404:
writeln .a3 == .a4
writeln "numbers: ", join ", ", [.a1, .a2, .a3, .a4, .a5]
writeln "letters: ", join ", ", map cp2s, [
{{out}}
Line 1,267 ⟶ 1,415:
=={{header|Lasso}}==
<
'A'->integer
97->bytes
65->bytes</
{{out}}<pre>97
65
a
A</pre>
=={{header|LFE}}==
In LFE/Erlang, lists and strings are the same, only the representation changes. For example:
<
"Don't Panic."</
As for this exercise, here's how you could print out the ASCII code for a letter, and a letter from the ASCII code:
<
97
ok
> (: io format '"~p~n" (list '(97)))
"a"
ok</
=={{header|Liberty BASIC}}==
<
char$ = "a"
print chr$(charCode) 'prints a
print asc(char$) 'prints 97</
=={{header|LIL}}==
LIL does not handle NUL bytes in character strings, char 0 returns an empty string.
<
print [codeat "a" 0]</
{{out}}
<pre>a
97</pre>
=={{header|Lingo}}==
<
put chartonum("a")
-- 97
Line 1,311 ⟶ 1,455:
-- returns character for Unicode code point (=ASCII code for ASCII characters)
put numtochar(934)
-- Φ</
=={{header|Little}}==
<
printf("The code 241 in Unicode is the letter: %c.\n", 241);
</syntaxhighlight>
=={{header|LiveCode}}==
<
put charToNum("") && numToChar(240)</
=={{header|Logo}}==
Logo characters are words of length 1.
<
print char 97 ; a</
=={{header|Logtalk}}==
<
a
Char = a
yes</
<
97
Code = 97
yes</
=={{header|Lua}}==
<
print(string.char(97)) -- prints "a"</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
\\ ANSI
Print Asc("a")
Line 1,365 ⟶ 1,503:
Print Codes("abcd")
\\ 97 98 99 100
</syntaxhighlight>
=={{header|Maple}}==
There are two ways to do this in Maple. First, there are procedures in StringTools for this purpose.
<
65
"A"
</syntaxhighlight>
Second, the procedure convert handles conversions to and from byte values.
<
[65]
> convert( [65], bytes );
"A"
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Use the FromCharacterCode and ToCharacterCode functions:
<
FromCharacterCode[{97}]</
{{Out}}<pre>{97, 98, 99, 100}
"a"</pre>
=={{header|MATLAB}} / {{header|Octave}}==
There are two built-in function that perform these tasks.
To convert from a number to a character use:
<
To convert from a character to its corresponding ascii character use:
<
or if you need this number as an integer not a double use:
<
asciiNumber = uint32(character)
asciiNumber = uint64(character)</
Sample Usage:
<
ans =
Line 1,420 ⟶ 1,555:
ans =
87</
=={{header|Maxima}}==
<
"A"
cint("A");
65</
=={{header|Metafont}}==
Metafont handles only ''ASCII'' (even though codes beyond 127 can be given and used as real ASCII codes)
<
string a;
a := readstring;
Line 1,444 ⟶ 1,577:
message char10; % (this add a newline...)
message char hex"c3" & char hex"a8"; % since C3 A8 is the UTF-8 encoding for "è"
end</
=={{header|Microsoft Small Basic}}==
<
TextWindow.WriteLine("The character for '65' is: " + Text.GetCharacter(65) + ".")</
{{out}}
<
The character for '65' is: A.
Press any key to continue...</
=={{header|MiniScript}}==
{{trans|Wren}}
MiniScript does not have a ''character'' type as such but one can use single character strings instead. Strings can contain any Unicode code point.
<syntaxhighlight lang="miniscript">cps = []
for c in ["a", "π", "字", "🐘"]
cp = c.code
cps.push cp
print c + " = " + cp
end for
print
for i in cps
print i + " = " + char(i)
end for</syntaxhighlight>
{{out}}
<pre>a = 97
π = 960
字 = 23383
🐘 = 128024
97 = a
960 = π
23383 = 字
128024 = 🐘
</pre>
=={{header|Modula-2}}==
<
IMPORT InOut;
Line 1,473 ⟶ 1,630:
InOut.Write (CHR (ascii));
InOut.WriteLn
END asc.</
{{out}}
<
a 97 1</
=={{header|Modula-3}}==
The built in functions <code>ORD</code> and <code>VAL</code> work on characters, among other things.
<
VAL(97, CHAR); (* Returns 'a' *)</
=={{header|MUMPS}}==
<
WRITE $CHAR(77)</
=={{header|Nanoquery}}==
<
println chr(97)
println ord("π")
println chr(960)</
{{out}}
<pre>97
Line 1,498 ⟶ 1,653:
960
π</pre>
=={{header|Neko}}==
Neko treats strings as an array of bytes
<
var s = "a";
var c = 98;
Line 1,510 ⟶ 1,664:
$sset(h, 0, c);
$print("Character code ", c, ": ", h, "\n");</
{{out}}
Line 1,518 ⟶ 1,672:
Neko also has standard primitives for handling the byte array as UTF-8
<
// native strings are just arrays of bytes
var us = "¥·£·€·$·¢·₡·₢·₣·₤·₥·₦·₧·₨·₩·₪·₫·₭·₮·₯·₹";
Line 1,539 ⟶ 1,693:
uc = 8356;
utfAdd(buf, uc);
$print("UTF-8 code ", uc, ": ", utfContent(buf), "\n");</
{{out}}
<pre>UFT-8 code for '€': 8364
UTF-8 code 8356: ₤</pre>
=={{header|NESL}}==
In NESL, character literals are prefixed with a backtick. The functions <tt>char_code</tt> and <tt>code_char</tt> convert between characters and integer character codes.
<
it =
<syntaxhighlight lang="nesl">code_char(97);
it = `a : char</syntaxhighlight>
=={{header|NetRexx}}==
NetRexx provides built-in functions to convert between character and decimal/hexadecimal.
<
options replace format comments java crossref symbols nobinary
Line 1,578 ⟶ 1,730:
say ci.right(3)"| '"cc"'" cd.right(6) cx.right(4, 0) "'"dc"' '"xc"'"
end ci
return</
{{Out}}
<pre style="height:20ex; overflow:scroll">' abcde$¢£¤¥₠₡₢₣₤₥₦₧₨₩₪₫€₭₮₯₰₱₲₳₴₵'
Line 1,616 ⟶ 1,768:
32| '₴' 8372 20B4 '₴' '₴'
33| '₵' 8373 20B5 '₵' '₵'</pre>
=={{header|Nim}}==
<
echo chr(97) # echoes a
Line 1,624 ⟶ 1,775:
echo int("π".runeAt(0)) # echoes 960
echo Rune(960) # echoes π</
=={{header|NS-HUBASIC}}==
NS-HUBASIC uses a non-ASCII character set that doesn't include letters in lowercase.
<
20 PRINT CHR$(38)</
{{Out}}
<pre> 0A
&</pre>
=={{header|Oberon-2}}==
<
IMPORT Out;
VAR
Line 1,645 ⟶ 1,794:
Out.Int(d,3);Out.Ln;
Out.Char(c);Out.Ln
END Ascii.</
{{Out}}<pre>
97
a</pre>
=={{header|Objeck}}==
<
97->As(Char)->PrintLine();</
=={{header|Object Pascal}}==
''See [[#Pascal|Pascal]]''
=={{header|OCaml}}==
<
Printf.printf "%c\n" (char_of_int 97); (* prints "a" *)</
The following are aliases for the above functions:
<
- : char -> int = <fun>
# Char.chr;;
- : int -> char = <fun></
=={{header|Oforth}}==
Oforth has not type or class for characters. A character is an integer which value is its unicode code.
<syntaxhighlight lang
{{out}}
Line 1,677 ⟶ 1,822:
97
</pre>
=={{header|OpenEdge/Progress}}==
<
CHR(97) SKIP
ASC("a")
VIEW-AS ALERT-BOX.</
=={{header|Oz}}==
Characters in Oz are the same as integers in the range 0-255 (ISO 8859-1 encoding). To print a number as a character, we need to use it as a string (i.e. a list of integers from 0 to 255):
<
{System.showInfo [97]} %% prints "a"</
=={{header|PARI/GP}}==
<
print(Strchr([72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]))</
=={{header|Pascal}}==
<
writeln(chr(97));</
=={{header|Plain English}}==
<syntaxhighlight>
\ Obs: The little-a byte is a byte equal to 97.
Write the little-a byte's whereabouts on the console.
Put 97 into a number.
Write the number's target on the console.
</syntaxhighlight>
=={{header|Perl}}==
===Narrow===
The code is straightforward when characters are all narrow (single byte).
<
use warnings;
use utf8;
Line 1,718 ⟶ 1,865:
}
print "\n";
}</
{{out}}
<pre> Character: A
Line 1,750 ⟶ 1,897:
===Wide===
Have to work a little harder to handle wide (multi-byte) characters.
<
use warnings;
use feature 'say';
Line 1,768 ⟶ 1,915:
'UTF-8', join('', map { sprintf "%x ", ord } (utf8::encode($c), split //, $c)),
'Round trip', join('', map { chr } @ordinals);
}</
{{out}}
<pre> Character: Δ̂
Line 1,793 ⟶ 1,940:
UTF-8: f0 9f 91 a8 e2 80 8d f0 9f 91 a9 e2 80 8d f0 9f 91 a7 e2 80 8d f0 9f 91 a6
Round trip: 👨👩👧👦</pre>
=={{header|Phix}}==
{{libheader|Phix/basics}}
Characters and their ascii codes are one and the same. (See also printf, %d / %s / %c.)
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #0000FF;">?</span><span style="color: #008000;">'A'</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,810 ⟶ 1,954:
=={{header|Phixmonti}}==
<
97 tochar print</
=={{header|PHP}}==
Here character is just a string of length 1
<
echo chr(97), "\n"; // prints "a"</
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
println(chr(97)),
println(ord('a')),
println(ord(a)).</syntaxhighlight>
{{out}}
<pre>a
97
97</pre>
=={{header|PicoLisp}}==
<
-> 97
: (char "字")
Line 1,828 ⟶ 1,980:
-> ("文" "字")
: (mapcar char @)
-> (25991 23383)</
=={{header|PL/I}}==
<
2 c character (1),
2 i fixed binary (8) unsigned;
c = 'a'; put skip list (i); /* prints 97 */
i = 97; put skip list (c); /* prints 'a' */</
=={{header|PowerShell}}==
Powershell does allow for character literals with [convert]
<
PowerShell does not allow for character literals directly, so to get a character one first needs to convert a single-character string to a char:
<
Then a simple cast to int yields the character code:
<
This also works with Unicode:
<
For converting an integral character code into the actual character, a cast to char suffices:
<
[char] 9786 # ☺</
=={{header|Prolog}}==
SWI-Prolog has predefined predicate char_code/2.
Line 1,858 ⟶ 2,007:
?- char_code(X, 97).
X = a.</pre>
=={{header|PureBasic}}==
PureBasic allows compiling code so that it will use either Ascii or a Unicode (UCS-2) encoding for representing its string content.
Line 1,864 ⟶ 2,012:
A one-character string is used here to hold the character and a numerical character type is used to hold the character code.
The character type is either one or two bytes in size, depending on whether compiling for Ascii or Unicode respectively.
<
;Results are the same when compiled for Ascii or Unicode
charCode.c = 97
Line 1,874 ⟶ 2,022:
Input()
CloseConsole()
EndIf</
This version should be compiled with Unicode setting and the source code to be encoded using UTF-8.
<
;UTF-8 encoding compiled for Unicode (UCS-2)
charCode.c = 960
Line 1,887 ⟶ 2,035:
Input()
CloseConsole()
EndIf</
=={{header|Python}}==
{{works with|Python|2.x}}
Line 1,894 ⟶ 2,041:
8-bit characters:
<
print chr(97) # prints "a"</
Unicode characters:
<
print unichr(960) # prints "π"</
{{works with|Python|3.x}}
Here character is just a string of length 1
<
print(ord('π')) # prints "960"
print(chr(97)) # prints "a" (will also work in 2.x)
print(chr(960)) # prints "π"</
=={{header|Quackery}}==
Line 1,925 ⟶ 2,071:
a
Stack empty.</pre>
=={{header|R}}==
<
text <- rawToChar(as.raw(ascii)); text</
=={{header|Racket}}==
<
(define (code ch)
Line 1,941 ⟶ 2,085:
(printf "The unicode number ~a is the character ~s\n" n (integer->char n)))
(char 97)
(char 955)</
=={{header|Raku}}==
(formerly Perl 6)
Both Perl 5 and Raku have good Unicode support, though Raku attempts to make working with Unicode effortless. Note that even multi-byte emoji and characters outside the BMP are considered single characters. Also note: all of these routines are built into the base compiler. No need to load external libraries. See [[wp:Unicode_character_property#General_Category|Wikipedia: Unicode character properties]] for explanation of Unicode property.
<syntaxhighlight lang="raku"
.put for
[ 'Character',
Line 1,953 ⟶ 2,096:
'Unicode script',
'Unicode block',
'Added in Unicode version',
'Ordinal(s)',
'Hex ordinal(s)',
Line 1,960 ⟶ 2,104:
'Round trip by name',
'Round trip by ordinal'
]».fmt('%
Z
[ $_,
Line 1,967 ⟶ 2,111:
.uniprops('Script').join(', '),
.uniprops('Block').join(', '),
.uniprops('Age').join(', '),
.ords,
.ords.fmt('0x%X'),
Line 1,976 ⟶ 2,121:
];
say '';
}</
{{out}}
<pre> Character: A
Character name: LATIN CAPITAL LETTER A
Unicode property: Lu
Unicode script: Latin
Unicode block: Basic Latin
Added in Unicode version: 1.1
Hex
UTF-
UTF-
UTF-16BE: 0041
Round trip by
Round trip by ordinal: A
Character: Α
Character name: GREEK CAPITAL LETTER ALPHA
Unicode property: Lu
Unicode script: Greek
Unicode block: Greek and Coptic
Added in Unicode version: 1.1
Hex
UTF-
UTF-
UTF-16BE: 0391
Round trip by
Round trip by ordinal: Α
Character: А
Character name: CYRILLIC CAPITAL LETTER A
Unicode property: Lu
Unicode script: Cyrillic
Unicode block: Cyrillic
Added in Unicode version: 1.1
Hex
UTF-
UTF-
UTF-16BE: 0410
Round trip by
Round trip by ordinal: А
Character: 𪚥
Character name: CJK UNIFIED IDEOGRAPH-2A6A5
Unicode property: Lo
Unicode script: Han
Unicode block: CJK Unified Ideographs Extension B
Added in Unicode version: 3.1
Hex
UTF-
UTF-
UTF-16BE: D869 DEA5
Round trip by
Round trip by ordinal: 𪚥
Character: 🇺🇸
Character name: REGIONAL INDICATOR SYMBOL LETTER U, REGIONAL INDICATOR SYMBOL LETTER S
Unicode property: So, So
Unicode script: Common, Common
Unicode block: Enclosed Alphanumeric Supplement, Enclosed Alphanumeric Supplement
Added in Unicode version: 6.0, 6.0
Hex
UTF-
UTF-
UTF-16BE: D83C DDFA D83C DDF8
Round trip by
Round trip by ordinal: 🇺🇸
Character: 👨👩👧👦
Character name: MAN, ZERO WIDTH JOINER, WOMAN, ZERO WIDTH JOINER, GIRL, ZERO WIDTH JOINER, BOY
Unicode property: So, Cf, So, Cf, So, Cf, So
Unicode script: Common, Inherited, Common, Inherited, Common, Inherited, Common
Unicode block: Miscellaneous Symbols and Pictographs, General Punctuation, Miscellaneous Symbols and Pictographs, General Punctuation, Miscellaneous Symbols and Pictographs, General Punctuation, Miscellaneous Symbols and Pictographs
Added in Unicode version: 6.0, 1.1, 6.0, 1.1, 6.0, 1.1, 6.0
Hex ordinal(s): 0x1F468 0x200D 0x1F469 0x200D 0x1F467 0x200D 0x1F466
UTF-
UTF-
UTF-16BE: D83D DC68 200D D83D DC69 200D D83D DC67 200D D83D DC66
Round trip by
Round trip by ordinal: 👨👩👧👦</pre>
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
Print Chr$(97)
Print Asc("a")
</syntaxhighlight>
=={{header|Red}}==
<
print to-integer first "a" ;; -> 97
print to-integer #"a" ;; -> 97
print to-binary "a" ;; -> #{61}
print to-char 97 ;; -> a
</syntaxhighlight>
=={{header|Retro}}==
<syntaxhighlight lang
=={{header|REXX}}==
REXX supports handling of characters with built-in functions (BIFs), whether it be hexadecimal, binary (bits), or decimal code(s).
===ASCII===
<
yyy= 'c' /*assign a lowercase c to YYY. */
yyy= "c" /* (same as above) */
Line 2,101 ⟶ 2,249:
say ' dec code: ' c2d(yyy) /* decimal */
say ' bin code: ' x2b( c2x(yyy) ) /* binary (as a bit string) */
/*stick a fork in it, we're all done with display*/</
'''output'''
<pre>
Line 2,117 ⟶ 2,265:
===EBCDIC===
<
yyy='c' /*assign a lowercase c to YYY */
yyy='83'x /*assign hexadecimal 83 to YYY */
Line 2,130 ⟶ 2,278:
say c2x(yyy) /*displays the value of YYY in hexadecimal. */
say c2d(yyy) /*displays the value of YYY in decimal. */
say x2b(c2x(yyy))/*displays the value of YYY in binary (bit string). */</
{{out}}
<pre>a
Line 2,136 ⟶ 2,284:
129
10000001</pre>
=={{header|Ring}}==
<
see ascii("a") + nl
see char(97) + nl
</syntaxhighlight>
=={{header|RPL}}==
{{in}}
<pre>
"a" NUM
97 CHR
</pre>
{{out}}
<pre>
2: 97
1: "a"
</pre>
=={{header|Ruby}}==
In Ruby 1.9 characters are represented as length-1 strings; same as in Python. The previous "character literal" syntax <tt>?a</tt> is now the same as <tt>"a"</tt>. Subscripting a string also gives a length-1 string. There is now an "ord" method of strings to convert a character into its integer code.
<
=> 97
> 97.chr
=> "a"</
=={{header|Run BASIC}}==
<
print asc("a") 'prints 97</
=={{header|Rust}}==
<
fn main() {
Line 2,166 ⟶ 2,323:
println!("{}", 'π' as u32);
println!("{}", from_u32(960).unwrap());
}</
{{out}}
<pre>97
Line 2,172 ⟶ 2,329:
960
π</pre>
=={{header|Sather}}==
<
main is
#OUT + 'a'.int + "\n"; -- or
Line 2,180 ⟶ 2,336:
#OUT + CHAR::from_ascii_int(97) + "\n";
end;
end;</
=={{header|Scala}}==
{{libheader|Scala}}
Scala supports unicode characters, but each character is UTF-16, so there is not a 1-to-1 relationship for supplementary character sets.
===In a REPL session===
<
res2: Int = 97
Line 2,196 ⟶ 2,351:
scala> "\uD869\uDEA5"
res5: String = 𪚥</
===Full swing workout===
Taken the supplemental character sets in account.
<
object CharacterCode extends App {
Line 2,241 ⟶ 2,396:
f"${"(" + UnicodeToInt(coll).toString}%8s) ${flags(coll)} ${getName(coll(0).toInt)} "
}.foreach(println)
}</
{{Out}}
<pre style="height:20ex; overflow:scroll">
Line 2,314 ⟶ 2,469:
65: 𠀀 "\uD840\uDC00" U+20000 (131072) NN HIGH SURROGATES D840
66: 𪚥 "\uD869\uDEA5" U+2A6A5 (173733) NN HIGH SURROGATES D869</pre>[http://illegalargumentexception.blogspot.nl/2009/05/java-rough-guide-to-character-encoding.html More background info: "Java: a rough guide to character encoding"]
=={{header|Scheme}}==
<
(display (integer->char 97)) (newline) ; prints "a"</
=={{header|Seed7}}==
<
writeln(chr(97));</
=={{header|SenseTalk}}==
<
put NumToChar(97)</
=={{header|SequenceL}}==
SequenceL natively supports ASCII characters.<br>
'''SequenceL Interpreter Session:'''
<
97
cmd:>intToAscii(97)
'a'</
=={{header|Sidef}}==
<
say 97.chr; # => 'a'</
=={{header|Slate}}==
<
97 as: String Character.</
=={{header|Smalltalk}}==
<
(Character value: 97) displayNl. "output a"</
{{works with|Smalltalk/X}}
Ansi Smalltalk defines <tt>codePoint</tt>
<
Transcript showCR:(Character codePoint:97).
Transcript showCR:(98 asCharacter).
Line 2,355 ⟶ 2,503:
'abcmøøse𝔘𝔫𝔦𝔠𝔬𝔡𝔢' do:[:ch |
Transcript showCR:ch codePoint
]</
{{out}}
<pre>97
Line 2,376 ⟶ 2,524:
120097
120098</pre>
=={{header|SmileBASIC}}==
<
PRINT ASC("a") '97</
=={{header|SNOBOL4}}==
Snobol implementations may or may not have built-in char( ) and ord ( ) or asc( ).
These are based on examples in the Snobol4+ tutorial and work with the native (1-byte) charset.
<
chr &alphabet tab(n) len(1) . chr :s(return)f(freturn)
chr_end
Line 2,397 ⟶ 2,543:
output = chr(65)
output = asc('A')
end</
{{Out}}
<pre>A
A
65</pre>
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "charcode" )
@( description, "Given a character value in your language, print its code (could be" )
@( description, "ASCII code, Unicode code, or whatever your language uses). For example," )
@( description, "the character 'a' (lowercase letter A) has a code of 97 in ASCII (as" )
@( description, "well as Unicode, as ASCII forms the beginning of Unicode). Conversely," )
@( description, "given a code, print out the corresponding character. " )
@( category, "tutorials" )
@( see_also, "http://rosettacode.org/wiki/Character_codes" )
@( author, "Ken O. Burtch");
pragma license( unrestricted );
pragma restriction( no_external_commands );
procedure charcode is
code : constant natural := 97;
ch : constant character := 'a';
begin
put_line( "character code" & strings.image( code ) & " = character " & strings.val( code ) );
put_line( "character " & ch & " = character code" & strings.image( numerics.pos( ch ) ) );
end charcode;</syntaxhighlight>
=={{header|SPL}}==
In SPL all characters are used in UTF-16LE encoding.
<
#.output("a -> ",x[1]," ",x[2])
x = [98,0]
#.output("98 0 -> ",#.str(x))</
{{out}}
<pre>
Line 2,414 ⟶ 2,584:
98 0 -> b
</pre>
=={{header|Standard ML}}==
<
print (Char.toString (chr 97) ^ "\n"); (* prints "a" *)</
=={{header|Stata}}==
The Mata '''ascii''' function transforms a string into a numeric vector of UTF-8 bytes. For instance:
<
1 2
+-------------+
1 | 206 177 |
+-------------+</
Where 206, 177 is the UTF-8 encoding of Unicode character 945 (GREEK SMALL LETTER ALPHA).
Line 2,432 ⟶ 2,600:
ASCII characters are mapped to single bytes:
<
1 2 3 4 5 6 7 8 9 10 11 12 13
+-------------------------------------------------------------------------------+
1 | 87 101 32 116 104 101 32 80 101 111 112 108 101 |
+-------------------------------------------------------------------------------+</
Conversely, the '''char''' function transforms a byte vector into a string:
<
I stand here</
=={{header|Swift}}==
The type that represent a Unicode code point is <code>UnicodeScalar</code>.
You can initialize it with a string literal:
<
println(c1.value) // prints "97"
let c2: UnicodeScalar = "π"
println(c2.value) // prints "960"</
Or, you can get it by iterating a string's unicode scalars view:
<
for c in s1.unicodeScalars {
println(c.value) // prints "97"
Line 2,458 ⟶ 2,625:
for c in s2.unicodeScalars {
println(c.value) // prints "960"
}</
You can also initialize it from a <code>UInt32</code> integer:
<
println(UnicodeScalar(i1)) // prints "a"
let i2: UInt32 = 960
println(UnicodeScalar(i2)) // prints "π"</
=={{header|Tailspin}}==
Tailspin works with Unicode codepoints
<
'abc' -> $::asCodePoints -> !OUT::write
'$#10;' -> !OUT::write
'$#97;' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 2,478 ⟶ 2,644:
a
</pre>
=={{header|Tcl}}==
<
puts [scan "a" %c] ;# ==> 97
puts [format %c 97] ;# ==> a
# Unicode is the same
puts [scan "π" %c] ;# ==> 960
puts [format %c 960] ;# ==> π</
=={{header|TI-83 BASIC}}==
TI-83 BASIC provides no built in way to do this, so in all String<-->List routines and anything else which requires character codes, a workaround using inString( and sub( is used.
In this example, the code of 'A' is displayed, and then the character matching a user-defined code is displayed.
<
Disp inString(Str1,"A
Input "CODE? ",A
Disp sub(Str1,A,1</
=={{header|TI-89 BASIC}}==
The TI-89 uses an 8-bit charset/encoding which is similar to ISO-8859-1, but with more mathematical symbols and Greek letters.
Line 2,504 ⟶ 2,667:
The below program will display the character and code for any key pressed. Some keys do not correspond to characters and have codes greater than 255.
The portion of the program actually implementing the task is marked with a line of “©”s.
<
Local k, s
ClrIO
Line 2,524 ⟶ 2,687:
EndIf
EndLoop
EndPrgm</
=={{header|Trith}}==
Characters are Unicode code points, so the solution is the same for Unicode characters as it is for ASCII characters:
<
97 chr print</
<
960 chr print</
=={{header|TUSCRIPT}}==
<
SET character ="a", code=DECODE (character,byte)
PRINT character,"=",code</
{{Out}}<pre>a=97</pre>
=={{header|uBasic/4tH}}==
uBasic/4tH is an integer BASIC, just like Tiny BASIC. However, the function ORD() is supported, just as CHR(). The latter is only allowed within a PRINT statement.
<syntaxhighlight lang="text">z = ORD("a") : PRINT CHR(z) ' Prints "a"</
=={{header|UNIX Shell}}==
<syntaxhighlight lang="bash">
Aamrun$ printf "%d\n" \'a
97
Aamrun$ printf "\x$(printf %x 97)\n"
a
Aamrun$
</syntaxhighlight>
=={{header|Ursa}}==
<
out (ord "a") endl console
# outputs the character 'a' given its value
out (chr 97) endl console</
=={{header|Ursala}}==
Character code functions are not built in but easily defined as reifications of
the character table.
<
#import nat
Line 2,560 ⟶ 2,726:
#cast %cnX
test = (chr97,asc`a)</
{{Out}}<pre>(`a,97)</pre>
=={{header|
<syntaxhighlight lang="Uxntal">
( uxnasm char-codes.tal char-codes.rom && uxncli char-codes.rom )
|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1
|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1
|0100
[ LIT "a ] print-hex
newline
#61 .Console/write DEO
newline
( exit )
#80 .System/state DEO
BRK
@print-hex
DUP #04 SFT print-digit #0f AND print-digit
JMP2r
@print-digit
DUP #09 GTH #27 MUL ADD #30 ADD .Console/write DEO
JMP2r
@newline
#0a .Console/write DEO
JMP2r</syntaxhighlight>
Output:
<pre>61
a</pre>
=={{header|VBA}}==
<syntaxhighlight lang="vba">Debug.Print Chr(97) 'Prints a
Debug.Print [Code("a")] ' Prints 97</syntaxhighlight>
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
'prints a
WScript.StdOut.WriteLine Chr(97)
Line 2,574 ⟶ 2,772:
'prints 97
WScript.StdOut.WriteLine Asc("a")
</syntaxhighlight>
=={{header|Vim Script}}==
The behavior of the two functions depends on the value of the option <code>encoding</code>.
<
echo char2nr("a")
"Prints 97
echo nr2char(97)
"Prints a</
=={{header|Visual Basic .NET}}==
<
Console.WriteLine(Asc("a")) 'Prints 97</
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main() {
println('a'[0]) // prints "97"
println('π'[0]) // prints "207"
s := 'aπ'
println('string cast to bytes: ${s.bytes()}')
for c in s {
print('0x${c:x} ')
}
}</syntaxhighlight>
{{out}}
<pre>
97
207
string cast to bytes: [a, 0xcf, 0x80]
97->0x61 207->0xcf 128->0x80
</pre>
=={{header|Wren}}==
Wren does not have a ''character'' type as such but one can use single character strings instead. Strings can contain any Unicode code point.
<
for (c in ["a", "π", "字", "🐘"]) {
var cp = c.codePoints[0]
Line 2,601 ⟶ 2,816:
var c = String.fromCodePoint(i)
System.print("%(i) = %(c)")
}</
{{out}}
Line 2,618 ⟶ 2,833:
=={{header|XLISP}}==
In a REPL:
<
#\a
[2] (CHAR->INTEGER #\a)
97</
=={{header|XPL0}}==
A character is represented by an integer value equal to its ASCII code.
Line 2,630 ⟶ 2,844:
character to an integer equal to its ASCII code.
<
ChOut(0, 97); \(Character Out) displays "a" on the console (device 0)</
=={{header|Z80 Assembly}}==
The Z80 doesn't understand what ASCII codes are by itself. Most computers/systems that use it will have firmware that maps each code to its corresponding glyph. Printing a character given its code is trivial. On the Amstrad CPC:
<
call &BB5a</
Printing a character code given a character takes slightly more work. You'll need to separate each hexadecimal digit of the ASCII code, convert each digit to ASCII, and print it. Once again, thanks to Keith of [[http://www.chibiakumas.com Chibiakumas]] for this code:
<
push af
and %11110000
Line 2,657 ⟶ 2,870:
jp PrintChar ;this is whatever routine prints to the screen on your system.
; It must end in a "ret" and it must take the accumulator as its argument.</
=={{header|Zig}}==
<
const unicode = std.unicode;
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try characterAsciiCodes(stdout);
try characterUnicodeCodes(stdout);
}
fn characterAsciiCodes(writer: anytype) !void {
try writer.writeAll("Sample ASCII characters and codes:\n");
// Zig's string is just an array of bytes (u8).
const message: []const u8 = "ABCabc";
for (message) |val| {
}
try writer.writeByte('\n');
}
fn characterUnicodeCodes(writer: anytype) !void {
try writer.writeAll("Sample Unicode characters and codes:\n");
const message: []const u8 = "あいうえお";
const utf8_view = unicode.Utf8View.initUnchecked(message);
Line 2,686 ⟶ 2,904:
while (iter.nextCodepoint()) |val| {
var array: [4]u8 = undefined;
}
try writer.writeByte('\n');
}</syntaxhighlight>
{{out}}
<pre>
'A' code: 65 [hexa: 0x41]
'B' code: 66 [hexa: 0x42]
Line 2,700 ⟶ 2,919:
'b' code: 98 [hexa: 0x62]
'c' code: 99 [hexa: 0x63]
Sample Unicode characters and codes:
'あ' code: 12354 [hexa: U+3042]
'い' code: 12356 [hexa: U+3044]
'う' code: 12358 [hexa: U+3046]
'え' code: 12360 [hexa: U+3048]
'お' code: 12362 [hexa: U+304a]</pre>
=={{header|zkl}}==
The character set is 8 bit ASCII (but doesn't care if you use UTF-8 or unicode characters).
<
(97).toChar() //-->"a"</
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: character_codes
input: a
output: 97
</syntaxhighlight>
=={{header|Zoea Visual}}==
[http://zoea.co.uk/examples/zv-rc/Character_codes.png Character Codes]
=={{header|ZX Spectrum Basic}}==
<
20 PRINT CODE "a": REM prints 97</
{{omit from|bc}}
{{omit from|GUISS}}
|