Fix SixBit parser

This commit is contained in:
BtbN 2019-04-15 15:05:01 +02:00
parent 52b8f1d846
commit ed3d2ba40e
3 changed files with 64 additions and 12 deletions

View File

@ -116,8 +116,7 @@ namespace eAmuseCore.KBinXML
XElement node = doc.Root;
bool nodesLeft = true;
while (nodesLeft && nodeBuf.Any())
while (nodeBuf.Any())
{
nodeBuf = nodeBuf.SkipWhile(b => b == 0);
@ -149,6 +148,14 @@ namespace eAmuseCore.KBinXML
}
Console.WriteLine("Name: " + name);
bool skip = true;
if (nodeType == XmlTypes.EndSection.type)
break;
if (skip)
continue;
}
}
}

View File

@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Collections;
using System.Numerics;
using System.Text;
using System.Linq;
using System;
@ -9,6 +10,45 @@ namespace eAmuseCore.KBinXML
static class SixBit
{
static readonly string charmap = "0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
static readonly Dictionary<char, byte> bytemap = new Dictionary<char, byte>();
static SixBit()
{
for (byte i = 0; i < charmap.Length; ++i)
bytemap[charmap[i]] = i;
}
public static byte[] Pack(string input)
{
if (input.Length > byte.MaxValue)
throw new ArgumentException("input string is too long", "input");
int padding = (8 - (input.Length * 6)) % 8;
BigInteger bits = new BigInteger(0);
try
{
foreach (byte i in input.Select(c => bytemap[c]))
{
bits <<= 6;
bits |= i;
}
}
catch (KeyNotFoundException)
{
throw new ArgumentException("input string contains invalid sixbit characters.", "input");
}
bits <<= padding;
return bits.ToByteArray().Append((byte)input.Length).Reverse().ToArray();
}
public static string Unpack(byte[] data)
{
IEnumerable<byte> nodeBuf = data.AsEnumerable();
return Unpack(ref nodeBuf);
}
public static string Unpack(ref IEnumerable<byte> nodeBuf)
{
@ -17,21 +57,21 @@ namespace eAmuseCore.KBinXML
int length_bits = length * 6;
int length_bytes = (length_bits + 7) / 8;
int padding = (8 - (length_bits % 8)) % 8;
BitArray barr = new BitArray(nodeBuf.Take(length_bytes).ToArray());
// bytes are in big endian order, BigInteger expects little endian, hence .Reverse() it.
BigInteger bits = new BigInteger(nodeBuf.Take(length_bytes).Reverse().ToArray());
nodeBuf = nodeBuf.Skip(length_bytes);
bits >>= padding;
StringBuilder res = new StringBuilder();
for (int i = 0, pos = length_bits - 1; i < length; ++i)
char[] res = new char[length];
for (int i = length - 1; i >= 0; --i)
{
int resI = 0;
for (int j = 0; j < 6; ++j, --pos)
if (barr.Get(pos))
resI |= 1 << j;
res.Append(charmap[resI]);
int idx = (int)(bits & 0x3f);
bits >>= 6;
res[i] = charmap[idx];
}
return res.ToString();
return new string(res);
}
}
}

View File

@ -49,6 +49,11 @@ namespace eAmuseTest
Console.WriteLine(BytesToString(rawData));
KBinXML kbinxml = new KBinXML(rawData);
Dictionary<int, int> dd = new Dictionary<int, int>();
dd[2] = 3;
Console.WriteLine("" + dd[2]);
Console.WriteLine("" + dd[1]);
}
private static string BytesToString(IEnumerable<byte> bytes)