2008-10-27, 09:21 AM
Devil's Sunrise Wrote:Yeah, everything in computer programming is binary, we all know that.
But it's rather tedious to x0r strings. You first got to split the strings into char arrays with the longest string as the array-length, then perform xor on each array, and then compile the char arrays into strings again.
What? You don't need to split anything. In C, you'd code something like:
Code:
char *p,*q;
for (p=a, q=b; *p != '\0' && *q != '\0'; p++, q++)
{
*p ^= *q;
*q ^= *p;
*p ^= *q;
}
/* add the tail of the (previously) longer string onto the shorter.
This assumes there was enough room for it there.
If there wasn't, we shouldn't be attempting to swap anyway,
as new memory would need to be allocated.
*/
if ((*p == '\0') && (*q != '\0'))
{
strcpy(q,p);
*q = '\0';
}
else if ((*p != '\0') && (*q == '\0')
{
strcpy(p,q);
*p = '\0';
}Obviously this is not very human-readable. It's only one step removed from assembly language.
Quote:I get your thinking though, it's possible. Just not efficient for programmer (time-consuming to make the code) nor efficient enough to make an extreme difference unless you swap values every millisecond. (Hell, I'm not even sure if it more efficient at all)
It's not more efficient in terms of time - either programming time or run time (although this may depend on your hardware/microcode). It is more efficient in terms of space.
Suppose each of these "variables" is a gigabyte in size. Blithely declaring a "temp" variable that can hold such a value, may swamp out your paging space and hang the computer. If you're lucky, it will only cause a "stack overrun" error, and crash your program.
But mostly this question is just an intellectual exercise.
In normal usage, one wouldn't be swapping large structures or even strings at all. One would be accessing them "by reference" ("by address", "pointers") and therefore the only thing that would need swapping is the pointers (usually an integer or two) and not the actual data.

