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

后端 未结 5 1998
一向
一向 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:57

    If you're reversing binary data from a file with different endianness you should probably use the ntoh* and hton* functions, which convert specified data sizes from network to host order and vice versa. ntohl for instance converts a 32 bit unsigned long from big endian (network order) to host order (little endian on x86 machines).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-02 01:09

    I would review the stl::swap and make sure it's optimized; after that I'd say you're pretty optimal for space. I'm reasonably sure that's time-optimal as well.

    0 讨论(0)
  • 2021-01-02 01:17

    If you need to reverse there is a chance that you can improve your algorithms and just use reverse iterators.

    0 讨论(0)
  • 2021-01-02 01:18

    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);
    }
    
    0 讨论(0)
提交回复
热议问题