Or, alternatively, I could store my students' pass/fail on an exam using a simplysimple stream of bits where 1
is pass and 0
is fail, and I know the order of my students based on some other data I've stored somewhere else (not in this file). This is a highly efficient storage mechanism in terms of data size, but it is also very inflexible in terms of storing additional information (e.g. absentees).
Here's an online converter so you can play around with this (you can press "Swap" to switch converting to or from binary).
In programming terms, your variable type matters, because it indicates to the compiler how your data should be stored, and how it should be handled.
int myNumber = 65535;
string myString = "65535";
In the first case, it will store your value numerically. 65535 (decimal) is 1111 1111 1111 1111
in binary. However, int
is always 4 bytes, so it gets stored as 0000 0000 0000 0000 1111 1111 1111 1111
. Total size: 4 bytes.
In the second case, it will store each individual text character, which we already know from before is 0011 0110 0011 0101 0011 0101 0011 0011 0011 0101
. Total size: 5 bytes.
Now here's an interesting curve ball:
int myNumberPlusOne = myNumber + 1;
string myStringPlusOne = myString + 1;
In the first case, because you're dealing with a number, the compiler does numerical addition, and stores the sum as a new number. myNumberPlusOne
is therefore stored as 0000 0000 0000 0001 0000 0000 0000 0000
, which is a value one bigger than myNumber
. Total size: still 4 bytes.
In the second case, because you're dealing with text, the compiler appends the 1
to the text. Now, you're storing a 6-character string, 655351
, which in binary is 0011 0110 0011 0101 0011 0101 0011 0011 0011 0101 0011 0001
. Total size: 6 bytes.
Here, you can see why data types matter. We store things differently, and we also treat that data differently. Why? Because it makes sense to us that +
on numbers means numerical addition, whereas +
on strings means string concatenation (= appending).