C memcpy 反向

发布于 2024-08-21 00:31:40 字数 142 浏览 2 评论 0原文

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我只土不豪 2024-08-28 00:31:40

不,memcpy 不会向后执行此操作。如果您使用 C 语言工作,请编写一个函数来完成它。如果您确实使用 C++ 工作,请使用 std::reverse 或 std::reverse_copy。

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.

孤者何惧 2024-08-28 00:31:40

这适用于反向复制 int

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];

}

就像 memcpy() 一样,dstsrc 指向的区域code> 不得重叠。

如果你想就地反转:

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

上面的两个函数都是可移植的。您可以通过使用特定于硬件的代码来使它们更快。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文