Byte to ASCII conversion Generating Unneeded/Undesired Spacing Characters

时间:2016-04-04 16:37:05

标签: c# type-conversion ascii whitespace

I have a code that relies heavily on bytes for its speed while not writing to a file.

In either the read function or the datapoint conversion function, I am getting several unnecessary "space" characters from the byte array after converting it to an ASCII string, even after setting them to NULL. This generates a lot of undesired whitespace. Here's parts of the current code:

//Within Read Function
var charBuf = Enumerable.Repeat<byte>(0, 1024).ToArray(); //Set byte array to null
int ret = Read(ConnectionID, charBuf, 1024); //Call to a custom dll to retrieve data
if (0 <= ret)
{
    return charBuf;
}

//Datapoint message is set as an empty byte that gets added to the list Datapoint
//The following converts the datapoint to a string depending on its input
var message = Encoding.ASCII.GetString(dataPoint.Message);
if (String.IsNullOrEmpty(message))
{
    message = "ReadError";
}

Is there any way to eliminate these supposed characters without too much code or is there an error in my conversion? Either fix would be appreciated.

1 个答案:

答案 0 :(得分:0)

为了防止修改代码的读取功能比改变数据类型以便优化代码的速度,我决定通过在读取后完成字符串简化的过程来处理空白空间问题函数不再使用,所有数据都写入文件:

            var message = Encoding.Default.GetString(dataPoint.Message);
            int messageSize=0;
            byte nullByte = 0x00;
            for (int k=0; k < dataPoint.Message.Count(); k++)
            {
                if (dataPoint.Message.ElementAt(k).Equals(nullByte))
                {
                    messageSize = k+1;
                    break;
                }
                else
                {
                    continue;
                }
            }
            message = message.Substring(0, messageSize);
然后,

消息将逐行附加到文本文件中,每行显示一条消息。

此方法确保尽管被定义为1024个空格,但只考虑读取函数接收的数据(接收的数据不发送空格)。