Menu

Character Sets

ASCII and Integer Values

A digit character such as '6' is stored as its ASCII code, not as the number it looks like. The character '6' has ASCII code 54, written in 7 bits as 0110110. That code tells the computer which character to display. It is not the same as the integer value 6, which can be stored as the 4-bit binary pattern 0110.

Storing a number as a binary integer uses fewer bits and lets the computer do arithmetic with it. Storing the same number as ASCII characters uses more bits and does not allow arithmetic directly, because the computer is holding character codes rather than numeric values.

What is storedExample for 6Bits usedCan you do arithmetic directly?
IntegerBinary 01104Yes: 6 + 3 = 9
ASCII characterCode 54, binary 01101107No: 54 + 53 = 107, the code for 'k'

The character codes must be converted to numeric values before calculations can be carried out. In Python, int('6') gives the integer 6, and ord('6') gives the ASCII code 54. You can then use the value in a calculation.

symbol = '6'
code = ord(symbol)   # ASCII code for the character
value = int(symbol)  # integer value of the digit
print(code)
print(value + 3)

Output:

54
9

The program shows the difference: ord() returns the character's code, while int() returns the number you need for arithmetic.

Practise this