I’ve never really liked hexadecimal notation. The combination of letters and numbers always made my brain turn off. I mean, I understand it, but it never seemed like it made a difference or not.
Binary
Obviously, computers think in ones and zeroes. The smallest unit is typically talked about as a byte, which consists of eight bits. Using those eight bits, we can count from 0 to 255. If you want a bigger number than that, you need to use more bytes.
Today, a typical integer is made up of 4 bytes (32 bits), which lets you have a range of 0 to 4,294,967,295 (if you don’t worry about negative numbers… otherwise you need to reserve one of those bits to say whether or not the number is negative, and your range goes to –2,147,483,648 to 2,147,483,647.
When you’re working with networking, especially when you need to send messages at a high frequency, being mindful of your data size is pretty important.
Say that you need to keep track of the day of the week. There’s only 7 possibilities, so you can get away with just one byte. If you used a normal, 32-bit integer, you’d be wasting 3 bytes every time you send that message.
If you need to send this information over the network one million times per day (for some reason), that’s 1 million bytes (1 megabyte) of data. If you used a 32-bit integer, suddenly that becomes 4 million bytes (4 megabytes), and 3 of those megabytes are actually not even used!
And that’s just for one particular field. Chances are, you’ll need to send more than just the day of the week. Maybe you need to send the time of day, too:
0 = Morning
1 = Mid-Morning
2 = Noon
3 = Afternoon
4 = Evening
5 = Night
If you used a 32 bit integer for both of those fields, your data consumption grows to 8 megabytes over the course of the day. You can see how this can get out of hand quickly.
Nibbles
So in our two examples, the day of the week and the time of day can both be represented by a single byte; but, actually, they can be represented by less than that. If you split a byte in half, you get a nibble: 4 bits, giving you the ability to store 0-15. We can easily store each component in a nibble, making it so our data consumption is back down to 1 megabyte despite having two fields.
But how do you deal with just half a byte?
Bit Shifting
In order to get each nibble out of a byte, you have to do some bit shifting (which is another thing you probably haven’t thought about in awhile)
Note that in C#, we have to cast the result as a byte because C# helpfully just assumes that you want a regular ol’ int when you’re doing a bitwise operation on a number.
Hex
The interesting thing I noticed about working with nibbles is that one byte can be represented by two hexadecimal characters, 0-F (0-15). This works out great because you can easily tell what each nibble is just by looking at the hexadecimal characters:
0x35 – first nibble = 5, second nibble = 3.
0xBE – first nibble = 14, second nibble = 11.