gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:17:52 27 4
gpt4 key购买 nike

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

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

source

问题

如何使用位移位将值转换回 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;
}

或者为了避免过多的输出参数,使用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;
}

一般问题:为什么在这里使用 int 而不是 byte

关于c# - 如何使用 BitShifting 将基于 int 的 IP 地址转换回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9775136/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com