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

后端 未结 5 1999
一向
一向 2021-01-02 00:19
typedef unsigned char Byte;

...

void ReverseBytes( void *start, int size )
{
    Byte *buffer = (Byte *)(start);

    for( int i = 0; i < size / 2; i++ ) {
             


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 00:58

    A performant solution without using the STL:

    void reverseBytes(void *start, int size) {
        unsigned char *lo = start;
        unsigned char *hi = start + size - 1;
        unsigned char swap;
        while (lo < hi) {
            swap = *lo;
            *lo++ = *hi;
            *hi-- = swap;
        }
    }
    

    Though the question is 3 ½ years old, chances are that someone else will be searching for the same thing. That's why I still post this.

提交回复
热议问题