B
BrianJones
Having programmed in java for many years, I decided to try C++ for speed...
Anyway, am writing this simple encryption program, and a method I have takes
an array of chars (i.e. bytes) and swaps the two halves around e.g:
0,1,2,3,4,5,6,7,8 -> 5,6,7,8,4,0,1,2,3
But - it doesn't work properly and I can't see the problem? Any suggestions?
The following is the method:
char* swap(char* bytes)
{ long pivot;
char *swappedBytes;
bool parity = false; // whether length odd or even
swappedBytes = new char[strlen(bytes)-1];
if(strlen(bytes)%2==0)
{
pivot = strlen(bytes)/2;
parity = false; // even
}
else
strlen(bytes)%2==1){
pivot = ((strlen(bytes)-1)/2);
parity = true; // odd
}
if(parity)//odd
{
for(int i = 0;i<pivot;i++){
swappedBytes = bytes[i+pivot+1];
}
for(int i = pivot+1;i<strlen(bytes);i++){
swappedBytes = bytes[i-pivot-1];
}
swappedBytes[pivot] = bytes[pivot];
}
else if(!parity)//even
{
for(int i=0;i<pivot;i++){
swappedBytes = bytes[i+pivot];
}
for(int i = pivot;i<strlen(bytes);i++){
swappedBytes = bytes[i-pivot];
}
}
return swappedBytes;
}
Thanks,
Ben
Anyway, am writing this simple encryption program, and a method I have takes
an array of chars (i.e. bytes) and swaps the two halves around e.g:
0,1,2,3,4,5,6,7,8 -> 5,6,7,8,4,0,1,2,3
But - it doesn't work properly and I can't see the problem? Any suggestions?
The following is the method:
char* swap(char* bytes)
{ long pivot;
char *swappedBytes;
bool parity = false; // whether length odd or even
swappedBytes = new char[strlen(bytes)-1];
if(strlen(bytes)%2==0)
{
pivot = strlen(bytes)/2;
parity = false; // even
}
else
strlen(bytes)%2==1){
pivot = ((strlen(bytes)-1)/2);
parity = true; // odd
}
if(parity)//odd
{
for(int i = 0;i<pivot;i++){
swappedBytes = bytes[i+pivot+1];
}
for(int i = pivot+1;i<strlen(bytes);i++){
swappedBytes = bytes[i-pivot-1];
}
swappedBytes[pivot] = bytes[pivot];
}
else if(!parity)//even
{
for(int i=0;i<pivot;i++){
swappedBytes = bytes[i+pivot];
}
for(int i = pivot;i<strlen(bytes);i++){
swappedBytes = bytes[i-pivot];
}
}
return swappedBytes;
}
Thanks,
Ben