c++arraysbyteint

C++ int to byte array


I have this method in my java code which returns byte array for given int:

private static byte[] intToBytes(int paramInt)
{
     byte[] arrayOfByte = new byte[4];
     ByteBuffer localByteBuffer = ByteBuffer.allocate(4);
     localByteBuffer.putInt(paramInt);
     for (int i = 0; i < 4; i++)
         arrayOfByte[(3 - i)] = localByteBuffer.array()[i];
     return arrayOfByte;
}

Can someone give me tip how can i convert that method to C++?


Solution

  • 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;
    }