Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to reverse an array of bytes in memory?

Tags:

c++

memory

std

swap

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

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.

EDIT: I just realized how bad the title I put for this question was, so I [hopefully] fixed it.

like image 223
xian Avatar asked Feb 25 '09 09:02

xian


People also ask

Why are bytes reversed?

Description. The Byte Reversal block changes the order of the bytes in the input data. Use this block when your process communicates between processors that use different endianness. For example, use this block for communication between Intel® processors that are little-endian and others that are big-endian.

What is reverse byte order?

Description. The Byte Reversal block changes the order of the bytes in data that you input to the block. Use this block when a process communicates between target computers that use different endianness, such as between Intel® processors that are little endian and other processors that are big endian.

How do you reverse bytes in Java?

Integer reverseBytes() Method in Java The java. lang. Integer. reverseBytes(int a) is a built-in method which returns the value obtained by reversing the order of the bytes in the two's complement representation of the specified int value.

How do you reverse Bytearray?

you can use the linq method: MyBytes. Reverse() as well as the Array. Reverse() method.


1 Answers

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);
}
like image 74
kmkaplan Avatar answered Sep 17 '22 11:09

kmkaplan