Converting Between ASCII Characters and Values
Problem
You want to print out the number represented by a given ASCII character, or you want to print out an ASCII character given a number.
Solution
Use ord to convert a character to a number, or use
chr to convert a number to a character:
$num = ord($char); $char = chr($num);
The %c format used in printf
and sprintf also converts a number to a character:
$char = sprintf("%c", $num); # slower than chr($num)
printf("Number %d is character %c\n", $num, $num);
Number 101 is character eA C* template used with pack
and unpack can quickly convert many characters.
@ASCII = unpack("C*", $string);
$STRING = pack("C*", @ascii);Discussion
Unlike low-level, typeless languages like assembler, Perl
doesn’t treat characters and numbers interchangeably; it treats
strings and numbers interchangeably. That means
you can’t just assign characters and numbers back and forth.
Perl provides Pascal’s
chr
and
ord to convert between a character and its
corresponding ordinal value:
$ascii_value = ord("e"); # now 101
$character = chr(101); # now "e"If you already have a character, it’s really represented as a
string of length one, so just print it out directly using
print or the %s format in
printf and sprintf. The
%c
format forces
printf or sprintf to convert a
number into a character; it’s not used for printing a character
that’s already in character format (that is, a string).
printf("Number %d is character %c\n", 101, 101);The
pack
,
unpack, chr, and
ord ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access