有更好的方法来反转内存中的字节数组吗? [英] Is there a better way to reverse an array of bytes in memory?
本文介绍了有更好的方法来反转内存中的字节数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
typedef unsigned char Byte;
...
void ReverseBytes( void *start, int size )
{
Byte *buffer = (Byte *)(start);
for( int i = 0; i < size / 2; i++ ) {
std::swap( buffer[i], buffer[size - i - 1] );
}
}
这种方法现在是反转字节记忆。我想知道的是,有更好的方法来获得相同的效果吗?整个size / 2部分似乎是一个坏东西,但我不知道。
What this method does right now is it reverses bytes in memory. What I would like to know is, is there a better way to get the same effect? The whole "size / 2" part seems like a bad thing, but I'm not sure.
编辑:我刚刚意识到我为这个问题
I just realized how bad the title I put for this question was, so I [hopefully] fixed it.
推荐答案
标准库有一个 std :: reverse
功能:
The standard library has a std::reverse
function:
#include <algorithm>
void ReverseBytes( void *start, int size )
{
char *istart = start, *iend = istart + size;
std::reverse(istart, iend);
}
这篇关于有更好的方法来反转内存中的字节数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文