C Macro/Function to Convert a IP Address into a 32-bit Integer

in #programming3 years ago

We know the IPv4 Address is 32-bit which consists of four integers from 0 to 255 inclusive. We can use a 32-bit integer to represent a valid IP address. The following is a C macro that #defines a procedure to convert a IP address (given four numbers) to a 32-bit integer.

#define IPV4_ADDR(a, b, c, d)(((a & 0xff) << 24) | ((b & 0xff) << 16) | \
        ((c & 0xff) << 8) | (d & 0xff))

We can also use the function implementation:

inline unsigned int 
getIPAddress(char a, char b, char c, char d) {
  return (((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff));
}

To convert a 32-bit integer back to a IP Address, we can shift the number to the right for 24, 16 and 8 bits.

--EOF (The Ultimate Computing & Technology Blog) --

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

Hi sir I'm Esha. I'm new here on steemit please do support and give me some guidelines.
Thank you 😊