Q:

Add value in char array last index using C++

I want to send array through socket.The length of array is 16 where last four bytes is value.
To make this dynamic I am trying to add value to the end of array.
I have unsigned char array
Eg: 
unsigned char command[] = { 0x40, 0x01, 0x00, 0x02, 0x00, 0x08, 0x11, 0x4c, 0x00, 0x00, 0xa1, 0x24 };

I want to add value at the end of this array.
int value = 380;

So hex representation of 380 is 17c
Now the array becomes
0x40, 0x01, 0x00, 0x02, 0x00, 0x08, 0x11, 0x4c, 0x00, 0x00, 0xa1, 0x24, 0x00, 0x00, 0x01, 0x7c

where last four byte is value.
I have try to add last four byte by first creating array which have values
char* temp = "00000380"

and then using for loop add this to new array 
Code
int m_imageX = 380;

char m_buf[3] = { '\0' };
int count = 0;
int value = 0;
int m_index;

unsigned char command[16];
unsigned char commandss[] = { 0x40, 0x01, 0x00, 0x02, 0x00, 0x08, 0x11, 0x4c, 0x00, 0x00, 0xa1, 0x24 };
for (m_index = 0; m_index < 12; m_index++)
{
    command[m_index] = commandss[m_index];
}

std::string m_tmp = std::to_string(m_imageX);
char const *tmp = m_tmp.c_str();
char comm[8];
int size = strlen(tmp);
for (int i = 0; i < 8 - size; i++)
{
    comm[i] = '0';
}
for (int i = 8 - size; i < 8; i++)
{
    comm[i] = tmp[count++];
}

count = 0;
for (int j = 0; j < 8; j++)
{

    if (j > 0  && j % 2 == 0)
    {
        command[m_index++] = atoi(m_buf);
        count = 0;
        memset(m_buf, NULL, sizeof(m_buf));
        m_buf[count++] = comm[j];
    }
    else
    {
        m_buf[count++] = comm[j];
    }
}

command[m_index] = atoi(m_buf);

But when I sending this I found on wireshark that the array transmitted has value like
    0x40, 0x01, 0x00, 0x02, 0x00, 0x08, 0x11, 0x4c, 0x00, 0x00, 0xa1, 0x24, 0x00, 0x00, 0x03, 0x50

So can anyone tell me how to do this

A:

Use shift and bitwise operators to break the integer in to bytes, and store in std::vector
0x17c & 0xFF results 0x7c. Right shift by 8 bits and repeat to get the next byte. The example below will add the bytes in big-endian format 00 00 01 7C:
#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<unsigned char> vec =
    { 0x40, 0x01, 0x00, 0x02, 0x00, 0x08, 0x11, 0x4c, 0x00, 0x00, 0xa1, 0x24 };

    int num = 380;
    std::vector<unsigned char> bytes;
    for(int i = 0; i < 4; i++)
    {
        bytes.insert(bytes.begin(), num & 0xFF);
        num = num >> 8;
    }

    for(auto e : bytes)
        vec.push_back(e);

    for(auto e : vec)
        std::cout << std::hex << (unsigned int)e << " ";
    std::cout << "\n";

    return 0;
}

output:

40 1 0 2 0 8 11 4c 0 0 a1 24 0 0 1 7c

