在一个通用的清单更换两个字节字节、清单、两个

2023-09-04 08:22:52 作者:青衫

我要替换的那些神奇的2个字节的包之一的每次出现在我的名单,其中,字节> 用一个字节:

I want to replace every occurrence of one of those magic 2-byte packages in my List<byte> with a single byte:

{0xF8时,0×00} - >替换为0xF8的   {0xF8时,0×01} - >替换0xFB的才能   {0xF8时,0X02} - >替换是0xFD   {0xF8时,0×03} - >替换0xFE的

{ 0xF8, 0x00 } -> Replace with 0xF8 { 0xF8, 0x01 } -> Replace with 0xFB { 0xF8, 0x02 } -> Replace with 0xFD { 0xF8, 0x03 } -> Replace with 0xFE

例如:

List<byte> message 
    = new List<byte> { 0xFF, 0xFF, 0xFB, 0xF8, 0x00, 0xF8, 0x01, 0xF8, 0x02, 0xF8, 0x03, 0xFE };

// will be converted to:

List<byte> expected 
    = new List<byte> { 0xFF, 0xFF, 0xFB, 0xF8, 0xFB, 0xFD, 0xFE, 0xFE };

这是我的解决方案,到目前为止,它的作品,但我不喜欢它,因为它的可读性是相当糟糕:

单片机复习

This is my solution so far, which works but I don't like it because its readability is quite bad:

public static void RemoveEscapeSequences(List<byte> message)
{
    // skipped parameter checks
    for (int index = 0; index < message.Count - 1; ++index)
    {
        if (message[index] == 0xF8)
        {
            // found an escaped byte, look at the following byte to determine replacement
            switch (message[index + 1])
            {
                case 0x0:
                    message[index] = 0xF8;
                    message.RemoveAt(index + 1);
                    break;
                case 0x1:
                    message[index] = 0xFB;
                    message.RemoveAt(index + 1);
                    break;
                case 0x2:
                    message[index] = 0xFD;
                    message.RemoveAt(index + 1);
                    break;
                case 0x3:
                    message[index] = 0xFE;
                    message.RemoveAt(index + 1);
                    break;
            }
        }
    }
}       

有没有改进的可读性,更短的解决方案吗?

Is there a shorter solution with improved readability?

推荐答案

您可以做这样的事情 - 它会稍微慢一点,但:

You can do something like this - it'll be slightly slower, though:

public static void RemoveEscapeSequences(List<byte> message)
{
    var replaceBytes = new Dictionary<byte, byte>()
    {
        {0x00, 0xF8}, {0x01, 0xFB}, {0x02, 0xFD}, {0x03, 0xFE}
    };

    // skipped parameter checks
    for (int index = 0; index < message.Count - 1; ++index)
    {
        if (message[index] == 0xF8)
        {
            if(replaceBytes.ContainsKey(message[index + 1]))
            {
                message[index] = replaceBytes[message[index + 1]];
                message.RemoveAt(index + 1);
            }
        }
    }
}  
 
精彩推荐
图片推荐