Search code examples
c#ipintbit-manipulationipv4

How do I use BitShifting to convert an int-based IP address back to a string?


The following code to converts an IP to an int in a very fast way:

  static int ipToInt(int first, int second, int third, int fourth)
    {
        return (first << 24) | (second << 16) | (third << 8) | (fourth);
    }

source

Question

How do I use bit shifting to convert the value back to an IP address?


Solution

  • Try the following

    static out intToIp(int ip, out int first, out int second, out int third, out int fourth) {
      first = (ip >> 24) & 0xFF;
      second = (ip >> 16) & 0xFF;
      third = (ip >> 8) & 0xFF;
      fourth = ip & 0xFF;
    }
    

    Or to avoid an excessive number of out parameters, use a struct

    struct IP {
      int first;
      int second; 
      int third;
      int fourth;
    }
    
    static IP intToIP(int ip) {
      IP local = new IP();
      local.first = (ip >> 24) & 0xFF;
      local.second = (ip >> 16) & 0xFF;
      local.third = (ip >> 8) & 0xFF;
      local.fourth = ip & 0xFF;
      return local;
    }
    

    General Question: Why are you using int here instead of byte?