c++arrayssortingmemcpy

memcpy for create int[] from byte[]


I have a byte array that stores an unsigned 16 bit number, and I want to use my personal memcpy() to create a function that will add zeros when creating an int array.

void* Mymem_cpy(void* dest, void* src, int n)
{
    if (dest == NULL) return NULL;
    char* char_dest = (char*)dest;
    char* char_src = (char*)src;

    for (int i = 0; i < n; i++) 
    {
        char_dest[i] = char_src[i]; 
    }

    return dest;
}


unsigned char bytes[8]{ 179, 16, 0, 0, 0, 40, 92, 0, 0 };

int IntArray[2];
Mymem_cpy(&IntArray bytes, 8);

After that, the IntArray array will contain 2 numbers (4275, and 23592), which is correct.

The problem is that the original bytes array looks like this

unsigned char bytesInput[4]{ 179, 16, 40, 92 };

Without zeros. Is it possible to rewrite the Mymem_cpy function so that it automatically sets zeros where I need them for this task?


Solution

  • You need just two indexes

    void* Mymem_cpy(void* dest, void* src, int n)
    {
        if (dest == NULL) return NULL;
        char* char_dest = (char*)dest;
        char* char_src = (char*)src;
    
        for (int s = 0, d = 0; s < n; s += 2, d += sizeof(int)) 
        {
            char_dest[d] = char_src[s];
            char_dest[d + 1] = char_src[s + 1];
            for (int j = 2; j < sizeof(int); ++j)
                char_dest[d + j] = 0;
        }
    
        return dest;
    }
    

    Alternatively use std::memset with zero at the function beginning instead of the inner loop.