Skip to content

Instantly share code, notes, and snippets.

@main--
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save main--/d23e6deb7ffd470ed610 to your computer and use it in GitHub Desktop.
Save main--/d23e6deb7ffd470ed610 to your computer and use it in GitHub Desktop.
BestBitstreamEUW
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BestBitstreamEUW
{
public static class Awesomeness
{
public static IEnumerable<bool> IterateBits(this byte[] arr)
{
foreach (var b in arr)
for (int i = 0; i < sizeof(byte) * 8; i++)
yield return ((b >> i) & 1) == 1;
}
public static uint ReadToUint(this IEnumerable<bool> stream)
{
int index = 0;
uint result = 0;
foreach (var bit in stream)
result |= ((bit ? 1u : 0u) << checked(index++));
if (index > 32)
throw new Exception("use IEnumerable.Take you scrub DansGame");
if (index <= 0)
throw new Exception("no bits -.-'");
return result;
}
public static IEnumerable<bool> OutputBits(this IEnumerable<bool> stream, int howMany, out uint result)
{
result = stream.Take(howMany).ReadToUint();
return stream.Skip(howMany);
}
public static IEnumerable<bool> OutputByte(this IEnumerable<bool> stream, out byte result)
{
uint res;
var ret = stream.OutputBits(8, out res);
result = checked((byte)res);
return ret;
}
public static IEnumerable<bool> OutputVarInt(this IEnumerable<bool> stream, out uint result)
{
int count = 0;
result = 0;
uint tmpByte;
do
{
if (count > 5)
throw new InvalidDataException("VarInt32 out of range");
stream = stream.OutputBits(8, out tmpByte);
result |= (tmpByte & 0x7F) << (7 * count);
count++;
}
while ((tmpByte & 0x80) != 0);
return stream;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment