如何在字节数组 C# 中转换具有随机长度的字符串

How do I turn a string with random length in array of bytes C#

我需要在字节数组中转换类似“0.014”的内容,其中第一个“0”= arr[0]、“.”= arr[1] 等等... 并将它们转换为 Little Endian。 我的代码工作正常,但我对字符串的长度有疑问,有时它会给出越界异常 这是我的代码:

public void convertErrToByte(string errString, byte[] errToByte3)
    {              
        string errString2 = "";
        byte[] errToByte = new byte[errString.Length];
        byte[] errToByte2 = new byte[errString.Length];       
        
        for (int i = 0; i < errString.Length; i++)
        {
            errToByte[i] = Convert.ToByte(errString[i]); 
        }
        try
        {
            for (int i = 0; i < errToByte.Length - 1; i += 2) 
            {
                errToByte2[i] = errToByte[i + 1];
                errToByte2[i + 1] = errToByte[i];
            }
        }
        catch (Exception ex) { MessageBox.Show(ex.ToString()); }
        for (int i = 0; i < errToByte2.Length; i++)
        {
            errString2 += errToByte2[i].ToString("X"); 
        }

        for (int i = 0; i < errString2.Length; i++)
        {
            errToByte3[i] = Convert.ToByte(errString2[i]); 
        }
    }

假设您使用的是 ASCII 编码:

    private void swapBytePair(ref byte[] bytes)
    {
        if (bytes.Length == 0)
            return;

        byte temp;
        int len = (bytes.Length % 2 == 0) ? bytes.Length : bytes.Length - 1;

        for (int i=0; i < len; i+=2)
        {
            temp = bytes[i];
            bytes[i] = bytes[i + 1];
            bytes[i + 1] = temp;
        }
    }

    byte[] bytes = Encoding.ASCII.GetBytes("ABCDEFG");
    swapBytePair(ref bytes);
    //result: "BADCFEG"

我认为你遇到了字符串长度不均匀的问题,我的方法忽略了最后一个字节,因为没有什么可以交换的。