我想更改任意C ++字符串(std::string
)
例如:01234567
更改为32107654
。我这样做
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;
}
并像这样打电话
char *swapped = bswap32("01234567");
std::cout << swapped << std::endl;
但我不确定,这是否是C ++中的有效方式.....
使用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;