LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

"Reverse" bytes in string

Hello,

 

I have a string like this : "ABCDEF"

I want to get this from this string : "EFCDAB".

 

What's the best way to do that in CVI ?

 

Thanks in advance,

Blue

 

0 Kudos
Message 1 of 15
(1,716 Views)

You are reversing 16bit words, not bytes here.

0 Kudos
Message 2 of 15
(1,704 Views)

Something along this line? (str1 and str2 must be previously allocated in the correct size)

for (i = 0; i < strlen (str1); i++) {
	str2[i] = str1[strlen (str1) - i - 1];
}


Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 3 of 15
(1,693 Views)

This is more a C question than a CVI question... You can do this in place without need for an extra allocation by using an intermediate short. Something like (untested, caveat if string len is odd, caveat if UTF, etc)

 

char Str[]="ABCDEF";
int L=strlen(Str);
short C, *SC=(short*)Str;
for (int i=0; i<L/4; i++) {
 C=SC[i];
 SC[i]=SC[L/2-i];
 SC[L/2-i]=C;
}

 

0 Kudos
Message 4 of 15
(1,689 Views)

Hello,

 

Roberto, this will gave me "FEDCBA" and not "EFCDAB".

0 Kudos
Message 5 of 15
(1,685 Views)

Hello gdargaud,

 

I will try this, thank you. 

0 Kudos
Message 6 of 15
(1,684 Views)

@BlueAnaconda  ha scritto:

Hello,

 

Roberto, this will gave me "FEDCBA" and not "EFCDAB".


Correct, I didn't focused on expected target string and the quotes around "reverse"



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 7 of 15
(1,680 Views)

gdargaud, 

 

The code I tested, it's not good too.

 

Roberto, Yes, do you have a suggestion please ? 

0 Kudos
Message 8 of 15
(1,670 Views)

This should work for any string with any number of couples of chars.
The lack of explanations and comments is not casual. 🤣

    char *s = "ABCDEF";
    int len = (int)strlen(s);
    int len2 = (len / 4) * 2; // ;-)

    char c1, c2;

    for (int i=0; i<len2; i+=2) {
        c1 = s[i];
        c2 = s[i+1];
        s[i]   = s[len-2-i];
        s[i+1] = s[len-1-i];
        s[len-2-i] = c1;
        s[len-1-i] = c2;
    }
Carlo A.
Megaris




0 Kudos
Message 9 of 15
(1,659 Views)

You can also make use of SwapBlock function in the Programmer's Toolbox:

#include "toolbox.h"
#include <ansi_c.h>
static int		i, len, duplets;
static char	str[64];

strcpy (str, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
len = strlen (str);
duplets = len / 2;

for (i = 0; i < duplets; i += 2) {
	SwapBlock (str + i, str + len - i - 2, 2);
}

 

 

Just my 2c... after my initial gaffe 😉



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 10 of 15
(1,653 Views)