How do I convert from 8 bit byte to 7 bit byte (Base 256 to Base 128)
I am looking to do something like this:
public string BytesToString(byte[] in)
{
}
It's a bit difficult to determine from your question (as it currently stands) what you're trying to achieve. Are you trying to do base-128 encoding, or are you trying to conver a series of (presumably hexadecimal) digits representing 7bit numbers into the equivalent binary 8bit numbers?
The encoding I just described is the one used in the ID3v2 tag format for encoding the size field in the header.
If this is what you're trying to achieve, then perhaps something like the code below will do the trick. It's based on the '257' example in the ID3 specification:
[Test]
public void GetInt()
{
var bytes = new byte[] { 0, 0, 2, 1};
var result = 0;
foreach (var b in bytes)
{
result <<= 7;
result = result + (b & 0x7f);
}
Assert.That(result, Is.EqualTo(257));
}
[Test]
public void SetInt()
{
var i = 257;
var bytes = new Stack();
for (var j = 0 ; j < sizeof(int) ; j++)
{
var b = (byte)(i & 0x7f);
bytes.Push(b);
i >>= 7;
}
Assert.That(bytes.Pop(), Is.EqualTo(0));
Assert.That(bytes.Pop(), Is.EqualTo(0));
Assert.That(bytes.Pop(), Is.EqualTo(2));
Assert.That(bytes.Pop(), Is.EqualTo(1));
}