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?
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
?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With