I'm having a problem translating some Pascal code into C. Basically, I have nested loops, where the loop incrementing 'k' is within the loop incrementing 'i'. In both cases, I want to execute the command "if i (right shifted by) k AND 1 = 1, then do the following {code}". In Pascal I have:
{Pascal Code}
...
for i:=0 to N-1 do begin j:=0; temp:=N/2;
for k:=0 to P-1 do begin if ((i shr k) and 1)=1 then...
Which I know works. I've plotted the data from the Pascal code and it is correct, so I assume this algorithm is what I want to replicate in C. In C I have:
/*C code*/
...
int i;
unsigned int k;
for(i=0;i<N;i++){
j=0;
temp=N/2;
for(k=0;k<P;k++){
if((unsigned int)i)>>k&&1==1){
/*do code*/
}
In debugging these lines, I am writing to files that show what the values for Pascal's "i shr k" and C's "i>>k" are. The first several lines of these files for each are:
Pascal's "i shr k":
0
0
0
0
0
0
0
0
0
1...
My C results for "i>>k" are:
C's "i>>k":
1
2
1
3
1
4
2
1
5
2...
I've also found that in the Pascal version, there are many more visits to the inside of the "if" statement for a given value for i. Any idea on what's going on here? I know that Pascal's "shr" is a logical shift and that C's ">>" is an arithmetic shift, but I thought that putting (unsigned int) typecast in front of the left operand of ">>" would fix that? Anybody have any advice on how to make my C statement equivalent to the Pascal statement? It would be very much appreciated !
Thanks for reading!
&&
is a logicaland
operation.&
is a bitwiseand
. – Fred Larsonand
in Pascal are both logical and bitwise operators – phuclv