Ones and Zeros
Feb 052018Programmers deal with many types of data: most programming languages have integers, booleans, floating point numbers, strings, lists, and more.
The word “type” has a specific meaning: each value has a type.
In Python the value 1
has the type int
, and the value 'Hello, world!'
has the type str
.
In Java the value 1
has the type int
, and the value "Hello, world!"
has the type String
.
Try the following in Python, and investigate the types of some other values:
>>> type(1)
<class 'int'>
>>> type('Hello, world!')
<class 'str'>
Try the following in the BlueJ code pad, and investigate the types of some other values:
>>> 1
1 (int)
>>> "Hello, world!"
"Hello, world!" (String)
Whatever type of data we’re dealing with, the data has to be represented in the computer somehow, otherwise we can’t compute with it. But computers don’t have different processors for calculating with numbers and strings, nor do they have separate memory for different data types.
You probably know that computers represent data in binary formats, using bits which each have a value of 1 or 0.(1) As an analogy, we can imagine that a single bit is a switch which is either on or off, and the computer’s memory is just a lot of these switches. Then, when we need to store some data, there are two questions:
- How many switches (bits) do we need to represent this type of data?
- What do the on/off (1 or 0) states of the switches mean? How do we use them to represent the value we want to store?
To make the analogy more concrete, imagine you’re in a room with some switches, and you want to store or transmit an integer value such as 100 or −73. You must leave the switches in some state representing the number, then exit the room, and when you come back later — or somebody else enters the room — can you or they work out, from just the switches, what number was stored? Try with the switches below.
(This interactive feature requires Javascript to be enabled in your browser.)
Solving this problem requires deciding on a scheme for what the bits should mean. Whatever scheme you come up with, you’ll have to use it consistently, and so will whoever else needs to make sense of your data. In the next post we’ll see the scheme which is used by almost all computers to represent numbers using bits like these.
Footnotes
- Computers are made of digital electronic components, so 1 and 0 are represented by two different voltage levels.
Comments