主机字节与网络字节的转换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;

namespace ConsoleApplication2
{
    class Program
    {
        private static byte[] HostToNet(long iValue)
        {
            byte[] buffer = BitConverter.GetBytes(iValue);
            Array.Reverse(buffer);
            return buffer;
        }

        private static long NetToHost(byte[] data, int index)
        {
            Array.Reverse(data, index, sizeof(long));
            return BitConverter.ToInt64(data, index);           
        }              

        static void Main(string[] args)
        {
            Console.WriteLine("原始数值:");
            long n1 = 0x1234567890ABCDEF;
            Console.WriteLine("字符:{0}	字节:{1}
", n1.ToString("X"), BitConverter.ToString(BitConverter.GetBytes(n1)));

            Console.WriteLine("主机->网络(方法1):");           
            byte[] byteN1 = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(n1));
            Console.WriteLine("字符:{0}	字节:{1}
", n1.ToString("X"), BitConverter.ToString(byteN1));

            Console.WriteLine("主机->网络(方法2):");
            byteN1 = HostToNet(n1);
            Console.WriteLine("字符:{0}	字节:{1}
", n1.ToString("X"), BitConverter.ToString(byteN1));

            Console.WriteLine("网络->主机(方法1):");
            n1 = IPAddress.NetworkToHostOrder(BitConverter.ToInt64(byteN1, 0));
            Console.WriteLine("字节:{0}	字符:{1}
", BitConverter.ToString(byteN1), n1.ToString("X"));

            Console.WriteLine("网络->主机(方法2):");
            byte[] orgbyteN1 = new byte[byteN1.Length];
            byteN1.CopyTo(orgbyteN1, 0);
            n1 = NetToHost(byteN1, 0);
            Console.WriteLine("字节:{0}	字符:{1}
", BitConverter.ToString(orgbyteN1), n1.ToString("X"));

            Console.WriteLine("字符串自动按网络(大端)转换:");
            string str = "abcd";
            byte[] byteS = Encoding.Default.GetBytes(str);
            Console.WriteLine("字符:{0}	字节:{1}", str, BitConverter.ToString(byteS));
            Console.WriteLine("字节:{0}	字符:{1}", BitConverter.ToString(byteS), Encoding.GetEncoding("gb2312").GetString(byteS));
        }
    }
} 


原文地址:https://www.cnblogs.com/siso/p/3692053.html