Advertisement
Guest User

Untitled

a guest
Apr 24th, 2014
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. public static byte[] BitArrayToByteArray(BitArray bits)
  2. {
  3. byte[] ret = new byte[bits.Length / 8];
  4. bits.CopyTo(ret, 0);
  5. return ret;
  6. }
  7.  
  8.  
  9. public static byte[] ToByteArray(this BitArray bits)
  10. {
  11. int numBytes = bits.Count / 8;
  12. if (bits.Count % 8 != 0) numBytes++;
  13.  
  14. byte[] bytes = new byte[numBytes];
  15. int byteIndex = 0, bitIndex = 0;
  16.  
  17. for (int i = 0; i < bits.Count; i++)
  18. {
  19. if (bits[i])
  20. bytes[byteIndex] |= (byte)(1 << (7 - bitIndex));
  21.  
  22. bitIndex++;
  23. if (bitIndex == 8)
  24. {
  25. bitIndex = 0;
  26. byteIndex++;
  27. }
  28. }
  29. return bytes;
  30. }
  31.  
  32. byte[] ret = new byte[(bits.Length + 7) / 8];
  33. bits.CopyTo(ret, 0);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement