Created
December 13, 2016 07:38
-
-
Save zhenlinyang/b692badb1e708442c9d72783fbeda285 to your computer and use it in GitHub Desktop.
Bit Operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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