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地址?
尝试以下操作
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
?