C++ int to byte array C++ int to byte array arrays arrays

C++ int to byte array


You don't need a whole function for this; a simple cast will suffice:

int x;static_cast<char*>(static_cast<void*>(&x));

Any object in C++ can be reinterpreted as an array of bytes. If you want to actually make a copy of the bytes into a separate array, you can use std::copy:

int x;char bytes[sizeof x];std::copy(static_cast<const char*>(static_cast<const void*>(&x)),          static_cast<const char*>(static_cast<const void*>(&x)) + sizeof x,          bytes);

Neither of these methods takes byte ordering into account, but since you can reinterpret the int as an array of bytes, it is trivial to perform any necessary modifications yourself.


Using std::vector<unsigned char>:

#include <vector>using namespace std;vector<unsigned char> intToBytes(int paramInt){     vector<unsigned char> arrayOfByte(4);     for (int i = 0; i < 4; i++)         arrayOfByte[3 - i] = (paramInt >> (i * 8));     return arrayOfByte;}


You can get individual bytes with anding and shifting operations:

byte1 =  nint & 0x000000ffbyte2 = (nint & 0x0000ff00) >> 8byte3 = (nint & 0x00ff0000) >> 16byte4 = (nint & 0xff000000) >> 24