Home > Net >  Why does my code in Java gives me the right result that I want, and in C it doesn't?
Why does my code in Java gives me the right result that I want, and in C it doesn't?

Time:02-10

I wrote a code in C and it didn't give me the result that I wanted, so I thought I'll try it in Java. And yes in Java it works but in C it doesn't and I don't really know why, and I would like to know. The wanted result for RS2 is 10000 and for LS2 is 11001. (The program shifts 2 positions left. I wrote it in the most simple way because I want to find where my fault is. And in the Java I just gave the ls and rs as given, but in C, I found them using the DES Simplified Version)

Main Code in Java:

int ls[]= {0,1,1,1,0}; 
int rs[]= {0,0,1,0,0}; 
int rs2[]=new int[5]; 
int ls2[]=new int[5];
    
for(int i=0;i<5-2;i  ) { 
 ls2[i]=ls[i 2];    
 rs2[i]=rs[i 2]; 
}

ls2[5-2]=ls[0]; 
ls2[5-1]=ls[1]; 
rs2[5-2]=rs[0]; 
rs2[5-1]=rs[0];

The code in C is exactly the same the only difference is that the rs,rs2,ls,ls2 are global variables.

#include<stdio.h>
#include<stdlib.h> //global variables. 
int key[]={0,1,0,1,0,0,1,1,0,0}; 
int plaintxt1[]={0,1,0,1,0,0,0,1}; 
int LS[5]; int RS[5]; int LS1[5]; 
int RS1[5]; int LS2[5]; int RS2[5]; 
int encKey1[8]; int encKey2[8]; 
int length  = sizeof(key)/sizeof(int); 
//const arrays for the encryption part. 
const int P4[]={2, 4, 3, 1}; 
const int P8[]={6, 3, 7, 4, 8, 5, 10, 9}; 
const int P10[]={3,5,2,7,4,10,1,9,8,6};
    
void generateKey(){ 
int tempKey[10];   
int i;   int temp1=LS[0]; 
int temp2=RS[0];  
int temp3=LS1[0];  
int temp4=RS1[0];  
int temp5=LS1[1];   
int temp6=RS1[1];   
int pos=2;
    
 for(i=0; i<length;i  ){
   tempKey[i]=key[P10[i]-1]; //doing the permutation 10 as the first step.
   }
    
  //divides the key into 2 subkeys.   
    int mid=(length)/2;   
    for(i=0;i<mid;i  ){
      LS[i]=tempKey[I];
      RS[i]=tempKey[i mid];   
    }
    
    //left shift by 1 every subkey.   
      for(i=0;i<mid-1;i  ){
        LS1[i]=LS[i 1];
        RS1[i]=RS[i 1]; 
      }
      LS1[mid-1]=temp1;   
      RS1[mid-1]=temp2;   
      
//combining the 2 subkeys into one key.   
for(i=0;i<mid;i  ){
  tempKey[i]=LS1[i];
  tempKey[i mid]=RS1[i];   
}   
int j=0;   
//now we can do the permutation 8.  
 for(i=2; i<length;i  ){
   encKey1[j]=tempKey[P8[j]-1];
   j  ;  
 }  
//left shift by 2 every subkey.   
**for(i=0;i<mid-2;i  ){
   LS2[i]=LS[i 2];
   RS2[i]=RS[i 2]; 
}   
LS2[mid-2]=temp3;   
LS2[mid-1]=temp5;   
RS2[mid-2]=temp4;   
RS2[mid-1]=temp6; 
}**
int main(){   
  generateKey(); 
}

CodePudding user response:

  •  Tags:  
  • Related