Could somebody please explain me how this exactly works.
I would like to know what is the math behind all this, why exactly these numbers am I getting for analog read when one of the buttons is pressed?
Take "exactly" out of your sentence and the sentence has the same meaning. Unless you really want to get down to the atoms.
It's because you have a voltage divider which changes depending on what button is being pressed.
Example of an "exact" resource: http://en.wikipedia.org/wiki/Voltage_divider
Use the schematic LarryD posted. R5 and the rest of the resistors create a voltage divider. Pull-up resistors vary from pin to pin and chip to chip, so let's just call it 30kohm. Even though yours probably won't be that value.
R6..R11 in series together creates a resistance of 13.2kohm. Using the R1 and R2 notation from the Wikipedia Article: So when no button is pressed the divider is R1 = 30k and R2 = 13.2k. Vout is the voltage on A5 and Vin is 5V (VCC for the Arduino board)
Vout = (R2 / (R1 + R2)) * Vin
Vout = (13.2k / (30k + 13.2k)) * 5 = 1.53volts
Since the A/D 1023 steps, this means each step is worth:
Steps: 5 volts / 1023 steps = 4.9mV
1.53V / 4.9mV = 312 steps
When S1 is closed in LarryD's schematic, R7..R11 get bypassed. So now your divider becomes R1=30k and R2 = R6 = 2.2K.
Vout = (2.2K / (30K + 2.2K)) * 5 = 0.342 volts.
0.342mV / 4.9mV = 70 Steps
When S1 is closed in LarryD's schematic, R8..R11 get bypassed while R6 and R7 are now in series. So R1=30K and R2=4.4k.
Vout = (4.4k / (30K + 2.2K)) * 5 = 0.639 volts
0.639mV / 4.9mV = 130 steps
And So on.
a = analogRead(5);
Start the habit now that whenever you access an analog pin use the "Ax" designator. This reading your code easier and makes the code portable across different Arduino boards.