fork download
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. int main()
  5. {
  6. long int myLong = 0x12340;
  7. unsigned char myArray[16] = {};
  8.  
  9. std::cout << "Initially: ";
  10. for (const auto& x : myArray)
  11. std::cout << std::setw(2) << std::setfill('0') << std::hex << static_cast<int>(x) << ' ';
  12. std::cout << std::endl;
  13.  
  14. size_t i = sizeof(myArray) / sizeof(myArray[0]); // Get one beyond last index of array
  15. for (size_t shift = 0; shift < sizeof(myLong) * 8 && i > 0; shift += 4)
  16. myArray[--i] = static_cast<unsigned char>((myLong >> shift) & 0x0f);
  17.  
  18. std::cout << "After : ";
  19. for (const auto& x : myArray)
  20. std::cout << std::setw(2) << std::setfill('0') << std::hex << static_cast<int>(x) << ' ';
  21. std::cout << std::endl;
  22. }
  23.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
Initially: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
After    : 00 00 00 00 00 00 00 00 00 00 00 01 02 03 04 00