Representing Pitch in the Computer
Usually, we refer each note on the keyboard with a letter-number pair, for
example, C4 or Eb3. However, when coding, referring to each note in this way
can be cumbersome. Instead, computer musicians tend to refer to each note with
a specific integer, using a standard known as "MIDI numbers". According to
MIDI, middle C—also known as C4—is represented as the integer 60. Then, C#4 is
61, D4 is 62, and so on. Counting down, B3 is 59, Bb3 is 58, and so on. It
turns out that MIDI number 0 is actually C-1, not C0 as you might expect.
Converting from MIDI Number to Note Name
Let's say you're given a random MIDI number—say 42—and you want to figure out
what note it is. To do so, you should take that number modulo 12. (If you're
not aware, the modulo operator—usually shown as a percent sign—provides the
remainder when the first number is divided by the second.) In this case, 42
modulo 12 is 6. This number represents the number of half steps above C. In
the case of 6, this is a tritone, meaning our note name is F#.
This mapping—from the integer 6 to the note name F#—is an example of what music
theorists refer to as "pitch class". Pitch class is simply a one-to-one
mapping between an integer and a note name. By convention, 0 is C. Therefore,
1 is C#, 2 is D, and so on up to 11 as B.
Converting from Note Name to MIDI Number
Let's try the other way around: going from a note name to a MIDI number. Let's
try to find the MIDI number for the note Eb3. Do to this, we need to count the
number of half steps from C-1 (which, remember, is MIDI number 0) up to Eb3.
While we can always do this manually, let's try and be more clever about it.
Since there are twelve notes in an octave, and four octaves between C-1 and C3,
we can find the MIDI number of C3 by multiplying 12 by 4: so 48. Then, to find
the Eb above C3, we add the pitch class of Eb to our MIDI number for C3: in
this case, 3 + 48, or 51.
While it is important to understand how to translate between note names and
MIDI numbers, in practice you may end up relying on online tables and
calculators to perform this conversion; some additional resources are given on
the page below this video.