Saturday, June 01, 2019

Tips to Quickly Perform Binary and CIDR Operations

I maintain ip-num, a typescript library for working with ASN, IPv4, and IPv6 numbers. The library provides representations of these internet protocol numbers with the ability to perform various IP related operations like parsing, validating etc. on them

One of the side effects of working on such a library is that I get to become conversant with some bit (yup, intended) of Networking concepts: binary numbers and how that feed into how IP numbering works.

For example, how to read CIDR notations and tell how many IP number is in a range, or given a CIDR notation, how to tell if it is valid or not.

This post is just a quick pen down of some of these operations that has to do with IP numbers and ranges that I have encountered and how I have learnt to perform them quickly in my head, or at-least, with the help of some minimal jotting on a piece of paper.

This post was initially meant as a single post, but it quickly grew too long, so I am only including the first tip in this post and split the rest into various mini posts. Find the links below:

How to quickly convert binary to decimal

At around the time I started ip-num, I stumbled on an algorithm that can be used to quickly convert binary number to decimal mentally. The steps was stated on this link, which unfortunately is no longer up, but the content can still be seen via the wayback machine here

It is a simple step, and instead of recreating it, I copy it as it is stated:

  • Start at the first ‘1’ on the left, and start with the mental number one
  • Move one digit right. If that digit is a zero, multiply your mental number by two. If it is a one, multiply your mental number by two and add one.
  • Repeat step 2 for every digit of the binary number

Applying these steps to convert the binary number 1011010:

  • 1011010 – We start at the first one. Our mental total: 1
  • 1011010 – Next digit is a zero; we double our mental number: 1 x 2 = 2.
  • 1011010 – Next digit is a one; we double our mental number and add one: 2 x 2 + 1 = 5
  • 1011010 – Another one; double and add one: 5 x 2 + 1 = 11
  • 1011010 – Zero; double: 11 x 2 = 22
  • 1011010 – One; double and add one: 22 x 2 + 1 = 45
  • 1011010 – And finally a zero; double: 45 x 2 = 90

Nifty right?



Next post: How to tell the size of IP number in a CIDR notation

No comments: