Skip to content

Instantly share code, notes, and snippets.

@zhenlinyang
Created December 13, 2016 07:38
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 zhenlinyang/b692badb1e708442c9d72783fbeda285 to your computer and use it in GitHub Desktop.
Save zhenlinyang/b692badb1e708442c9d72783fbeda285 to your computer and use it in GitHub Desktop.
Bit Operation
public static class Bit
{
private const int INT_MAX_LENGTH = 32;
private const byte BYTE_MAX_LENGTH = 8;
public static bool Read(int source, int index)
{
Debug.Assert(index >= 0 && index < INT_MAX_LENGTH);
return 0 != (source & (1 << index));
}
public static bool Read(byte source, int index)
{
Debug.Assert(index >= 0 && index < BYTE_MAX_LENGTH);
return Read((int) source, index);
}
public static int Write(int source, int index, bool b)
{
Debug.Assert(index >= 0 && index < INT_MAX_LENGTH);
return b ? source | (1 << index) : source & ~(1 << index);
}
public static byte Write(byte source, int index, bool b)
{
Debug.Assert(index >= 0 && index < BYTE_MAX_LENGTH);
return (byte) Write((int) source, index, b);
}
public static bool[] IntToBitArr(int source)
{
var ret = new bool[INT_MAX_LENGTH];
for (byte index = 0; index < INT_MAX_LENGTH; index++)
{
ret[index] = 0 != (source & (1 << index));
}
return ret;
}
public static bool[] ByteToBitArr(byte source)
{
var ret = new bool[BYTE_MAX_LENGTH];
for (byte index = 0; index < BYTE_MAX_LENGTH; index++)
{
ret[index] = 0 != (source & (1 << index));
}
return ret;
}
public static int BitArrToInt(bool[] source)
{
var ret = 0;
for (byte index = 0; index < INT_MAX_LENGTH; index++)
{
if (source.Length > index && source[index])
{
ret |= 1 << index;
}
}
return ret;
}
public static byte BitArrToByte(bool[] source)
{
byte ret = 0;
for (byte index = 0; index < BYTE_MAX_LENGTH; index++)
{
if (source.Length > index && source[index])
{
ret |= (byte) (1 << index);
}
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment