ASCIIHexDecode,RunLengthDecode

时间:2021-10-11 19:50:02
 public static byte[] ASCIIHexDecode(byte[] data)
{
MemoryStream outResult = new MemoryStream();
bool first = true;
int n1 = ;
for (int k = ; k < data.Length; ++k)
{
int ch = data[k] & 0xff;
if (ch == '>')
break;
if (isWhitespace(ch))
continue;
int n = getHex(ch);
if (n == -)
throw new Exception("Illegal character in ASCIIHexDecode.");
if (first)
n1 = n;
else outResult.WriteByte((byte)( ((n1 << ) + n)));
first = !first;
}
if (!first)
outResult.WriteByte((byte)((n1 << )));
return outResult.ToArray();
} public static bool isWhitespace(int ch)
{
return (ch == || ch == || ch == || ch == || ch == || ch == );
} public static int getHex(int v)
{
if (v >= '' && v <= '')
return v - '';
if (v >= 'A' && v <= 'F')
return v - 'A' + ;
if (v >= 'a' && v <= 'f')
return v - 'a' + ;
return -;
}
public static byte[] RunLengthDecode(byte[] data)
{ // allocate the output buffer
MemoryStream outResult = new MemoryStream();
int dupAmount = -;
for (int i = ; i < data.Length; i++)
{
if ((dupAmount = (int)data[i]) != - && dupAmount != )
{
if (dupAmount <= )
{
int amountToCopy = dupAmount + ;
for (int j = ; j < amountToCopy; j++)
{
if (++i < data.Length)
{
outResult.WriteByte((byte)( data[i]));
}
else
{
break;
}
}
}
else
{
if (++i < data.Length)
{
byte dupByte = data[i];
for (int j = ; j < - (int)(dupAmount & 0xFF); j++)
{
outResult.WriteByte((byte)(dupByte));
}
}
}
}
else
{
break;
}
}
return outResult.ToArray();
}