fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using byte = unsigned char;
  5.  
  6. std::vector<uint16_t> GetIntArrayFromByteArray(const std::vector<byte>& byteArray)
  7. {
  8. const int inputSize = byteArray.size();
  9. const bool inputIsOddCount = inputSize % 2 != 0;
  10. const int finalSize = (int)(inputSize/2.0 + 0.5);
  11. // Ignore the last odd item in loop and handle it later
  12. const int loopLength = inputIsOddCount ? inputSize - 1 : inputSize;
  13.  
  14. std::vector<uint16_t> intArray;
  15. // Reserve space for all items
  16. intArray.reserve(finalSize);
  17. for (int i = 0; i < loopLength; i += 2)
  18. {
  19. intArray.push_back((uint16_t)((byteArray[i] << 8) | byteArray[i + 1]));
  20. }
  21.  
  22. // If the input was odd-count, we still have one byte to add, along with a zero
  23. if(inputIsOddCount)
  24. {
  25. // The zero in this expression is redundant but illustrative
  26. intArray.push_back((uint16_t)((byteArray[inputSize-1] << 8) | 0));
  27. }
  28. return intArray;
  29. }
  30.  
  31. int main() {
  32. const std::vector<byte> numbers{2,0,0,0,1,0,0,1,4};
  33. const std::vector<uint16_t> result(GetIntArrayFromByteArray(numbers));
  34.  
  35. for(uint16_t num: result) {
  36. std::cout << num << "\n";
  37. }
  38.  
  39. return 0;
  40. }
  41.  
  42.  
Success #stdin #stdout 0s 4376KB
stdin
Standard input is empty
stdout
512
0
256
1
1024