簡體   English   中英

搜索字符串並轉換為字節C#

[英]search string and and convert to byte c#

我想從txt文件中獲取特定的字符串,然后將字符串轉換為字節,例如,我有此txt文件:

; “一”

id_number:* = 344E6F4D6F7265486178785454332100

; “二”

id_number:* = 3536336A775E3825246E773543563437

; “三”

id:_number * = BDBD2EB72D82473DBE09F1B552A8983

現在,我要搜索的是標題,然后獲取標題的id_number,然后將其轉換為類似這樣的字節作為標題:

TWO(byte [] two = new byte [] {0xBD,0xBD,0x2E,0xB7,0x2D,0x82,0x47,0x3D,0xBE,0x09,0xF1,0x1B,0x55​​,0x2A,0x89,0x83};

我嘗試這樣做,但沒有用:

    string[] s = File.ReadAllLines("MyFilePath.txt");
List<byte[]> byteArrays = new List<byte[]>();
foreach (string st in s.Where(x => x.Trim().StartsWith("id_number:*=")).Select(x => x.Skip(12)))
{
    byte[] b = new byte[(int)((st.Length + 1) / 2)];
    for (int i = 0; i < (int)((st.Length + 1) / 2); i++)
    {
        var byteString = (st.Skip(2 * i).Length > 2) ?  st.Skip(2 * i).Take(2) : "0"+st.Skip(2 * i);
        var bt = Convert.ToByte(byteString, 16);
        b[i] = bt;
    }
    byteArrays.Add(b);
}

我現在不可以在哪里放標題?

請幫忙

selman22說的是正確的。

我對您的代碼進行了更改,以使其正常工作。 這是工作代碼。

string[] s = File.ReadAllLines(@"E:\test\test.txt");
var byteArrays = new List<byte[]>();
foreach (string st in s.Where(x => x.Trim().StartsWith("id_number:*=")).Select(x => new string(x.Skip(12).ToArray())))
{
    byte[] b = new byte[(int)((st.Length + 1) / 2)];
    for (int i = 0; i < (int)((st.Length + 1) / 2); i++)
    {
        var byteString = ((st.Skip(2 * i).Count() > 2) ? new string(st.Skip(2 * i).Take(2).ToArray()) : "0" + new string(st.Skip(2 * i).ToArray()));
        var bt = Convert.ToByte(byteString, 16);
        b[i] = bt;
    }
    byteArrays.Add(b);
}

暫無
暫無

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

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