1
0

wa_bits_operation.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. #include "WAT.h"
  2. unsigned char* wa::bits_operation::GetBits(unsigned char* Source, unsigned int NbrOfBits, unsigned int* BufferSize)
  3. {
  4. // check for wrong parameter
  5. if (Source == nullptr || NbrOfBits == 0 || BufferSize == nullptr)
  6. return nullptr;
  7. // variable
  8. unsigned int bitMask = 0;
  9. unsigned int nbrOfByteToRead = 1 + (NbrOfBits-1) / 8;
  10. unsigned char* bufferToReturn = (unsigned char*)malloc(nbrOfByteToRead);
  11. memset(bufferToReturn, 0, nbrOfByteToRead);
  12. *BufferSize = nbrOfByteToRead;
  13. // copy all bytes
  14. if (nbrOfByteToRead > 1)
  15. {
  16. memcpy(bufferToReturn, Source, nbrOfByteToRead - 1);
  17. }
  18. // copy the specific end bits
  19. bitMask = (1 << NbrOfBits - ((nbrOfByteToRead - 1)*8)) - 1;
  20. bufferToReturn[nbrOfByteToRead - 1] = Source[nbrOfByteToRead - 1] & bitMask;
  21. return bufferToReturn;
  22. }
  23. wa::strings::wa_string wa::bits_operation::PrintInBinary(unsigned char* buffer, unsigned int size)
  24. {
  25. wa::strings::wa_string ToReturn = "";
  26. for (unsigned int NbrOfByte = 0; NbrOfByte < size; ++NbrOfByte)
  27. {
  28. for (int IndexBit = 0; IndexBit < 8; ++IndexBit)
  29. ToReturn.append((buffer[NbrOfByte] & (1 << IndexBit)) ? "1" : "0");
  30. ToReturn.append(" ' ");
  31. }
  32. return ToReturn;
  33. }