簡體   English   中英

如何在字節數組 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"

我認為您遇到了字符串長度不均勻的問題,我的方法忽略了最后一個字節,因為沒有什么可以交換的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM