0

I want to change the endianness of arbitrary C++ string (std::string)

Ex : 01234567 change to 32107654. I do this

char *bswap32(const char *src) 
{
    char *dest = (char *)malloc(sizeof(char) * strlen(src));
    int idx = 0;
    while (idx < strlen(src)) {
        for (int i = 0; i<4; i++) {
            dest[i + idx] = src[idx + 3 - i];
        }
        idx += 4;
    }
    return dest;
}

And call like this

char *swapped = bswap32("01234567");
std::cout << swapped << std::endl;

But I'm not sure, is it the efficient way in C++ .....

Updated with use of std::string

std::string Sbswap32(const std::string src) 
{
    std::string dest (src.length(), ' ');
    size_t idx = 0;
    while (idx < src.length()) {
        for (int i = 0; i<4; i++) {
            dest.insert(i + idx, 1, src[idx + 3 - i]);
        }
        idx += 4;
    }
    return dest;
}

std::string sTest = "01234567";
std::string Sswapped = Sbswap32(sTest _8);
std::cout << Sswapped << std::endl;
LeMoussel
  • 5,290
  • 12
  • 69
  • 122

0 Answers0