Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 279
makerofthings7 Avatar asked Mar 19 '12 17:03

makerofthings7


2 Answers

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?

like image 65
JaredPar Avatar answered Oct 23 '22 18:10

JaredPar


Assuming your code above is correct, simply reverse the bit-shifts and AND the result with 0xFF to drop spurious bits:

first = (ip >> 24) & 0xff;
second = (ip >> 16) & 0xff;
third = (ip >> 8) & 0xff;
fourth = ip & 0xff;
like image 34
George Skoptsov Avatar answered Oct 23 '22 17:10

George Skoptsov