Semaphores: Bits and Bytes
Each of the bytes that makes up the RAM memory in SPLat consists of 8 bits. Bit stands for BInary digiT.
One bit is the electronic equivalent of an on/off switch. It can represent just two values, on and off (or yes/no or true/false). Very often the two values are referred to as the numbers 1 and 0.
There are 8 bits in a byte. Why 8 was picked as the magic number is partly historic, partly technical, but that’s how it is. By convention the bits in a byte are numbered 0-7, starting from the right:
| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
Similarly, the bytes within RAM memory are numbered from 0 up, so the first byte is 0, the 2nd is 1, etc. The number of a byte is called its address.
Consider the following grid, which represents the first few bytes of memory.
| Bit number | ||||||||
| Byte address | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| 0 | ||||||||
| 1 | ||||||||
| 2 | X | |||||||
| 3 | ||||||||
The bit marked X is bit 4 in byte 2
Imagine now if we start at the beginning of RAM and number the bits sequentially, not starting back at 0 for each byte.
| Byte address | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| 0 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| 1 | 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
| 2 | 23 | 22 | 21 | X | 19 | 18 | 17 | 16 |
| 3 | 31 | 30 | 29 | 28 | 27 | 26 | 25 | 24 |
The bit marked X is bit 20 in this new numbering scheme.
Imagine now if we shift the point where we start counting bits from byte address 0 to byte address 2. We get the following table:
| Byte address | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| 0 | ? | ? | ? | ? | ? | ? | ? | ? |
| 1 | ? | ? | ? | ? | ? | ? | ? | ? |
| 2 | 7 | 6 | 5 | X | 3 | 2 | 1 | 0 |
| 3 | 15 | 16 | 14 | 13 | 12 | 10 | 8 | 8 |
The X bit has now become number 4. The bits in bytes 0 and 1 no longer have numbers in this scheme, because negative numbers are too hard to contemplate.
What we have done is to move the base address from byte 0 to byte 2. Every semaphore instruction in SPLat allows you to specify a base address as well as the bit number. However, the base address is an optional argument, and if you leave it out it defaults to 0. That means you can happily ignore it if you are content with accessing just the first 32 bytes of RAM (256 bits) as semaphores. If you do use the base address you will be able to get up to 1024 semaphores in 128 bytes of RAM, and you will be able to do interesting things like indexed addressing of semaphores.
Obviously, if you explicitly state the base address you will have to do some advance planning of where you are going to place particular semaphores, both in terms of absolute memory address and relative to the base address you intend to use in your instructions. This applies doubly if you are going to index the base address.