C语言 C memcpy 反向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2242498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:26:45  来源:igfitidea点击:

C memcpy in reverse

creversememcpy

提问by Aran Mulholland

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 memcpythat will copy in reverse order. i.e. if I had 1,2,3,4 stored in an array, could I call memcpyand magicallyreverse them so I get 4,3,2,1.

我正在处理音频数据。我想反向播放示例文件。数据存储为无符号整数并打包得很好。有没有办法调用memcpy它将以相反的顺序复制。即如果我有 1,2,3,4 存储在一个数组中,我可以调用memcpy神奇地反转它们,所以我得到 4,3,2,1。

采纳答案by Alok Singhal

This works for copying ints in reverse:

这适用int于反向复制s:

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 dstand srcmust not overlap.

就像memcpy(),指向dst和的区域src不能重叠。

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.)

(我还没有测试代码的正确性。)

回答by janm

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.

不,memcpy 不会倒退。如果您使用 C 语言,请编写一个函数来执行此操作。如果您真的使用 C++,请使用 std::reverse 或 std::reverse_copy。