Simple binary operations just confused me

DISCLAIMER: This is really pretty basic stuff. – I was just really tired the other night and couldn’t really grasp all the 1’s and 0’s.

Anyway, just to set things straight, and in case someone else might be stuck with a similar problem, here’s a quick explanation.

To follow the example from the other day:

We have two numbers taken from our Facility and Priority enumerations and have selected 19 and 3. We know that the maximum value for the first number is 23 and for the second it’s 7.

In the example, we will be storing the result in single byte. In case you’ve forgotten how binary works, each bit, starting right to left, is twice the value of the bit before. I’ll try to illustrate how this looks:

 128 64 32 16 8 4 2 1

So the maximum value you can store in 8 bits is 255. Now with the basics down, on to how the method for calculating the PRI field in a syslog message:

Calculating the PRI value

We know that the maximum facility value is 23 and the maximum priority is 7. Using the method for calculating the PRI value, that gives us a maximum possible value of 19x8+7=159 and thus we can easily stay within the bounds of a single byte.

Moving onwards:

The Facility number 19 in binary would be

 0 0 0 1 0 0 1 1

We multiply 19x8. In binary terms, multiplying by 8 is the same as left-shifting your bits 3 places:

 1 0 0 1 1 0 0 0

Okay, now we add the priority value (3) to the above value. That gives us

 1 0 0 1 1 0 1 1

Converted to decimal, this gives 155 (surprise! this was also what we got when we did our little sum: 19x8+3).

Getting back to where we started

So now, to convert back to the original values, here’s what goes on.

To find the Facility (19), we simply right-shift our value 3 places (we left-shifted before, remember, by multiplying by 8?)

so, right-shift this 3 places:

 1 0 0 1 1 0 1 1

and we end up with:

 0 0 0 1 0 0 1 1

Which is the same as the original Facility number we started out with.

Now to find the priority number, we take our 8 bits and find the values in the three least-significant bits (three bits because the maximum value of the priority field is 7). This is done using an AND operation:

 1 0 0 1 1 0 1 1

&

 0 0 0 0 0 1 1 1

=

 0 0 0 0 0 0 1 1

Which is 3 :-)

So the magic isn’t really all that magic at all. It’s just a question of knowing where your bits are (no pun intended!)

The above method can easily be extended to house pretty much any values (or more of them) – it’s just a question of shifting back and forth and keeping track of what is where.