C# - 将数字序列转换为字节

0 c# bytearray

我正在尝试按顺序发送与数字1-1000对应的字节的UDP数据包.如何将每个数字(1,2,3,4,...,998,999,1000)转换为所需的最小字节数,并将它们放入我可以作为UDP数据包发送的序列中?

我试过以下但没有成功.任何帮助将不胜感激!

 List<byte> byteList = new List<byte>();

        for (int i = 1; i <= 255; i++)
        {
            byte[] nByte = BitConverter.GetBytes((byte)i);
            foreach (byte b in nByte)
            {
                byteList.Add(b);
            }
        }

        for (int g = 256; g <= 1000; g++)
        {
            UInt16 st = Convert.ToUInt16(g);
            byte[] xByte = BitConverter.GetBytes(st);
            foreach (byte c in xByte)
            {
                byteList.Add(c);
            }
        }


        byte[] sendMsg = byteList.ToArray();
Run Code Online (Sandbox Code Playgroud)

谢谢.

Moa*_*ini 6

你需要使用:

BitConverter.GetBytes(INTEGER);
Run Code Online (Sandbox Code Playgroud)