Reputation: 119
Please help me how to add these values into dictionary? I want to remove entire switch statement and to use Dictionary instead of it to store values and return int value to method. How can it be done?
private int ControlDecode(byte b)
{
int itype = -1;
int ipacekttype = b & 0x0F;
switch (ipacekttype)
{
case 0x01:
if ((b & 0xF0) == 0x10 || (b & 0xF0) == 0x20 || (b & 0xF0) == 0x50 || (b & 0xF0) == 0x60)
itype = 0x11;
break;
case 0x02:
if ((b & 0xF0) == 0x20 || (b & 0xF0) == 0x60 || (b & 0xF0) == 0x10 || (b & 0xF0) == 0x50)
itype = 0x12;
break;
case 0x03:
if ((b & 0xF0) == 0x00 || (b & 0xF0) == 0x10 || (b & 0xF0) == 0x20 || (b & 0xF0) == 0x40 || (b & 0xF0) == 0x50 || (b & 0xF0) == 0x56)
itype = 0x13;
break;
case 0x04:
if ((b & 0xF0) == 0x30 || (b & 0xF0) == 0x70)
itype = 0x14;
break;
case 0x05:
if ((b & 0xF0) == 0x00 || (b & 0xF0) == 0x10 || (b & 0xF0) == 0x20 || (b & 0xF0) == 0x40 || (b & 0xF0) == 0x50 || (b & 0xF0) == 0x56)
itype = 0x15;
break;
case 0x06:
if ((b & 0xF0) == 0x30 || (b & 0xF0) == 0x70)
itype = 0x16;
break;
case 0x08:
itype = 0x38;
break;
case 0x09:
itype = 0x39;
break;
case 0x0A:
itype = 0x3A;
break;
case 0x0B:
itype = 0x3B;
break;
case 0x0C:
itype = 0x3C;
break;
default:
break;
}
return itype;
}
Upvotes: 1
Views: 71
Reputation: 3907
This function would return the same result using a dictionary map instead of a switch statement.
private int ControlDecode(byte b)
{
int ipacekttype = b & 0x0F;
if (ipacekttype >= 0x08 && ipacekttype <= 0x0C)
return 0x30 + ipacekttype;
var map = new Dictionary<int, int>
{
{0x11, 0x11 }, {0x21, 0x11 }, {0x51, 0x11 }, {0x61, 0x11 },
{0x12, 0x12 }, {0x22, 0x12 }, {0x52, 0x12 }, {0x62, 0x12 },
{0x03, 0x13 }, {0x13, 0x13 }, {0x23, 0x13 }, {0x43, 0x13 }, {0x53, 0x13 }, /*{0x56, 0x13 }, */
{0x34, 0x14 }, {0x74, 0x14 },
{0x05, 0x15 }, {0x15, 0x15 }, {0x25, 0x15 }, {0x45, 0x15 }, {0x55, 0x15 }, /*{0x56, 0x15 }, */
{0x36, 0x16 }, {0x76, 0x16 },
};
return map.ContainsKey(b) ? map[b] : -1;
}
Note: There are two bugs in your logic that I've stressed by commenting out their values in the map. My guess is that it's a copy-paste error. They should PROBABLY be replaced by 0x63
and 0x65
respectively.
Upvotes: 2