简体   繁体   中英

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

I need to turn something like "0.014" in array of bytes, where first "0" = arr[0], "."= arr[1] and so on... and also turn them to Little Endian. My code works fine, but I have a problem with the length of the string and sometimes it gives out of bound exception Here is my code:

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]); 
        }
    }

Assuming you are using ASCII Encoding:

    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"

I think you had issues with uneven string lengths, my method ignores the last byte, since there is nothing to swap with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM