关于c#的问题:将一个整型以字符串IP地址的格式打印出来

用字符串表示的IP地址的格式是“”,但IP地址在内存中是一个unsigned int,字符串格式就是将这个unsigned int的4个字节unsigned char分别转换成字符串,然后中间用小数点隔开。编写程序,使用指针技术,将一个unsigned int以字符串IP地址的格式打印出来。

  • 以下回答由chatgpt基于相关博客总结生成:

    首先声明一个无符号32位整数类型的变量,并给它赋值:

    uint ipInt = 1200381700;
    

    然后使用指针技术进行转换:

    byte* pBytes = (byte*)&ipInt;
    string ipString = $"{*pBytes}.{*(pBytes + 1)}.{*(pBytes + 2)}.{*(pBytes + 3)}";
    

    这样就得到了表示IP地址的字符串形式。完整示例代码如下:

    using System;
    
    namespace Example
    {
        class Program
        {
            unsafe static void Main(string[] args)
            {
                uint ipInt = 1200381700;
                byte* pBytes = (byte*)&ipInt;
                string ipString = $"{*pBytes}.{*(pBytes + 1)}.{*(pBytes + 2)}.{*(pBytes + 3)}";
                Console.WriteLine(ipString);
            }
        }
    }
    

    输出结果为:

    71.85.134.76