C memcpy in reverse

淺唱寂寞╮ 提交于 2019-11-30 14:55:48

问题


I am working with audio data. I'd like to play the sample file in reverse. The data is stored as unsigned ints and packed nice and tight. Is there a way to call memcpy that will copy in reverse order. i.e. if I had 1,2,3,4 stored in an array, could I call memcpy and magically reverse them so I get 4,3,2,1.


回答1:


This works for copying ints in reverse:

void reverse_intcpy(int *restrict dst, const int *restrict src, size_t n)
{
    size_t i;

    for (i=0; i < n; ++i)
        dst[n-1-i] = src[i];

}

Just like memcpy(), the regions pointed-to by dst and src must not overlap.

If you want to reverse in-place:

void reverse_ints(int *data, size_t n)
{
    size_t i;

    for (i=0; i < n/2; ++i) {
        int tmp = data[i];
        data[i] = data[n - 1 - i];
        data[n - 1 - i] = tmp;
    }
}

Both the functions above are portable. You might be able to make them faster by using hardware-specific code.

(I haven't tested the code for correctness.)




回答2:


No, memcpy won't do that backwards. If you're working in C, write a function to do it. If you're really working in C++ use std::reverse or std::reverse_copy.



来源:https://stackoverflow.com/questions/2242498/c-memcpy-in-reverse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!