如何使用BitShifting将基于int的IP地址转换回字符串?

goo*_*ate 7 c# ip int bit-manipulation ipv4

以下代码以非常快的方式将IP转换为int:

  static int ipToInt(int first, int second, int third, int fourth)
    {
        return (first << 24) | (second << 16) | (third << 8) | (fourth);
    }
Run Code Online (Sandbox Code Playgroud)

资源

如何使用位移将值转换回IP地址?

Jar*_*Par 4

尝试以下操作

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;
}
Run Code Online (Sandbox Code Playgroud)

或者为了避免过多的输出参数,请使用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;
}
Run Code Online (Sandbox Code Playgroud)

一般问题:为什么使用int此处而不是byte