面试官:如果存取IP地址,用什么数据类型比较好 (C#版本)

受到这篇文章的影响,C#版本也可以实现IP的存取
MySQL如何有效的存储IP地址及字符串IP和数值之间如何转换

逻辑右移就是不考虑符号位,右移一位,左边补0
算术右移需要考虑符合位,右移一位,若符号位为1,就在左边补1,否则补0
算术右移也可以进行有符号位的除法,右移n位就等于2的n次方
205的二进制数是11001101 右移一位
逻辑右移 [0]1100110
算术右移 [1]1100110

    public class IpLongUtils
    {
        /**
             * 把字符串IP转换成long
             *
             * @param ipStr 字符串IP
             * @return IP对应的long值
             */
        public static long ip2Long(string ipStr)
        {
            string[] ip = ipStr.ToLower().Split(new string[]{"http",":","/","."},System.StringSplitOptions.RemoveEmptyEntries);
            return (long.Parse(ip[0]) << 24) + (long.Parse(ip[1]) << 16)
                    + (long.Parse(ip[2]) << 8) + long.Parse(ip[3]);
        }

        /**
         * 把IP的long值转换成字符串
         *
         * @param ipLong IP的long值
         * @return long值对应的字符串
         */
        public static string long2Ip(long ipLong)
        {
            var ipStr= $"{ipLong >> 24}.{(ipLong >> 16) & 0xFF}.{(ipLong >> 8) & 0xFF}.{ipLong & 0xFF}";
            return ipStr;
        }
    }
Debug.WriteLine(IpLongUtils.ip2Long("http://192.168.1.1"));
Debug.WriteLine(IpLongUtils.ip2Long("192.168.0.1"));
Debug.WriteLine(IpLongUtils.long2Ip(3232235521L));
3232235777
3232235521
192.168.0.1

原文地址:https://www.cnblogs.com/androllen/p/15616725.html