Binary Flags

Posted on Jan 10 2005 05:21pm by Luke Davison

I was talking to my friend Toby earlier today, bitching to him about binary flags. I was stuck on an issue with them and was havng a hell of a time getting it sorted out, since I wasn't sure what the flags needed to be.

Anyways, I was having a hard time explaining to him how it works as he is not a developer, but a network guru. So, I put it in his world, since I could demonstrate to him the same process using IP addresses and subnet masks. Another example is the umask in *nix operatin systems. After trying to explain it, I thought I'd put together some sample code showing how this works in the networking world.

Here is a C example showing how one would get the "valid" subnet mask for an IP address:

Toggle C Source for subnet_lookup.c:

The important part of this starts with:

  msb = *(unsigned char *) &adr_inet.sin_addr.s_addr;    if ((msb & 0x80) == 0x00) {       class = 'A';       netmask = "255.0.0.0";   } 

This returns the IP you specified on the command line in the correct format. We then combine that with a hex value to see if it is equal to another hex value. Since IP addresses and subnet masks are 32bit binary, when &'d together, it's like doing binary addition. And how does that work you might ask? Here is an example:

  1 + 1 = 10 (which is 0, you would carry the 1)   0 + 1 = 1   0 + 0 = 0   1 + 0 + 0 = 1   1 + 1 + 0 = 10 (again this is 0, you would carry the 1)   1 + 1 + 1 = 1 (this would be 11, you would carry the 1 here too) 

Okay, confused yet? Good! No, seriously though, it's pretty easy since you can only use 1's or 0's. Here is a more complete example of how binary values would be added together:

01101 + 10111 = 100100  This is why:    0 1 1 0 1 +  1 0 1 1 1 ------------- 1 0 0 1 0 0 

Not so bad huh? Starting from the right, we take 1 + 1, which REALLY is 10. So, it becomes 0, and you "carry" the 1. With me still? great! So, now we take 1 + 0 + 1, which again is 10. This too becomes 0 and you "carry" the 1 again. This time, we take 1 + 1 + 1, which is 11. If you've been following along, you would make it 1, then "carry" the 1.

Anyways, I've rambled way more then I intended to. If you haven't gotten it figured out by now, you either A) have no hope at all, B) consult the Oracle.

 

Comments

Nensi said:
Technology can be accept credit card most broadly defined as the entities, both material and immaterial, created by the application of mental and physical effort in isp order to achieve some value. In this usage, technology refers to tools and machines that may be used to solve real-world problems. It is a far-reaching backup software term that may include simple tools, such as a crowbar or wooden spoon, or more complex machines, such as a space station or particle accelerator. Tools and machines need not be material; virtual technology, such as computer software and business methods, fall file recovery under this definition of technology.