簡體   English   中英

在 C# 中將字符串轉換為字節數組以字節為單位獲取零

[英]converting string to byte array in c# getting zeros in bytes

我使用下面的代碼將 .key 擴展文件中的數據讀取到字節數組,我得到 16 個字節的輸出,但所有字節都為零。

在此處輸入圖片說明

System.IO.StreamReader myFile = new System.IO.StreamReader(Server.MapPath("ELECTRI.KEY"));
    string myString = myFile.ReadLine();
    string str = myString;


     //string str = myString.Substring(0, myString.Length - 2);         

    BitArray bit = new BitArray(str.Length);
    for (int i = 0; i < str.Length; i++)
    {
        if (str.Substring(i, 1) == "1")
        {
            bit[i] = true;
        }
        else
        {
            bit[i] = false;
        }
    }
    int numBytes = bit.Count;
    if (bit.Count % 8 != 0) numBytes++;
    keyyy = new byte[numBytes];
keyyy = new byte[numBytes];

這句話的意思是用new byte[numBytes]初始化keyyy ,所以所有的字節都是零。 你必須分配每個

這是填充數組所需的代碼

int numBytes = bit.Count;
if (bit.Count % 8 != 0) numBytes++;
keyyy = new byte[numBytes];
bit.CopyTo(keyyy, 0);

編輯

byte[] keyyy = File.ReadAllBytes("ELECTRI.KEY");

我想如果我現在正確理解您的問題,這樣做很簡單!

這是您可以解決問題的另一種方法:

string str = "1111111100000000";
byte[] keyyy = new byte[str.Length / 8]
    .Select((b, index) => Convert.ToByte(str.Substring(index * 8, 8), 2)).ToArray();

此語句使用Substring將字符串拆分為 8 個字符的組(忽略余數)。 然后使用Convert.ToByte每個 8 個字符的字符串(即11111111 )轉換為一個byte Convert.ToByte參數2讓我們的方法知道它是一個 base2 二進制字符串。

嘗試這個:

        byte[] buffer;

        using (StreamReader reader= new StreamReader("PATH HERE")) {
            var input = reader.ReadToEnd();
            buffer = Encoding.UTF8.GetBytes(input);
        }

PS:這將讀取整個文件內容。

暫無
暫無

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

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