使用BitConverter时插入的空格

时间:2014-03-03 20:49:41

标签: c# byte ascii bitconverter

当我将Queue<byte>列表转换为字符串进行比较时,我遇到了在字符之间插入某种空格的问题。但是,我不认为它们是实际的空白字符,因为Queue只保留七个值,而在调试时我仍然可以看到七个字符值。见图:

相关代码:

Queue<byte> bufKeyword = new Queue<byte>(7);

    // Remove old byte from queue and add new one
    if (bufKeyword.Count == 7) bufKeyword.Dequeue();
    bufKeyword.Enqueue((byte)fsInput.ReadByte());

    // Check buffer string for match
    StringBuilder bufKeywordString = new StringBuilder();

    foreach (byte qByte in bufKeyword) { 
        bufKeywordString.Append(Encoding.ASCII.GetString(BitConverter.GetBytes(qByte))); 
    }

    string _bufKeywordString = bufKeywordString.ToString();
    Console.WriteLine("{0}", _bufKeywordString); //DEBUG - SEE IMAGE

    StringBuilder bufWriteString = new StringBuilder();
    if (_bufKeywordString.StartsWith("time=")) //Does not work because of 'whitespace'
    {
        for (int i = 1; i < 25; i++) { bufWriteString.Append(fsInput.ReadByte()); }     // Read next 24 bytes
        fileWriteQueue.Enqueue(bufWriteString.ToString());                              // Add this data to write queue
        fileWriteQueueCount++;
        fileBytesRead += 24;                                                            // Change to new spot in file
    }

1 个答案:

答案 0 :(得分:3)

BitConverter.GetBytes参数没有bytebyte转换为shortBitConverter.GetBytes(short)返回两个元素的数组。

所以而不是

bufKeywordString.Append(Encoding.ASCII.GetString(BitConverter.GetBytes(qByte)));

bufKeywordString.Append(Encoding.ASCII.GetString(new byte[] {qByte});