1
votes

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!

1
Why are you doing a typecast from int i to unsigned int i when you can just cast i to uint in the first place?Eugene K
Hint: && is a logical and operation. & is a bitwise and.Fred Larson
Yeah I saw that, but since Pascal's "and" is a logical operator then wouldn't I want to use "&&" in C? And I know it's silly to typecast i like that so i'm just gonna go ahead and change that now...thanks :)user3763879
you're missing the point that and in Pascal are both logical and bitwise operatorsphuclv
I'm not seeing the same prints in my i>>k test, I'm not sure how you generated 1,2,1,3... from i>>k.Eugene K

1 Answers

4
votes

Your problem appears to be with operator precedance.

In the Pascal version, your condition is this:

((i shr k) and 1)=1

In the C version, your condition is this (with some brackets added to show precedance):

(i >> k) && (1==1)

Also, && is a logical operator, not a bitwise operator. The equivalent bitwise operator is &. If you add some brackets and switch operators, you should get what you want:

((i >> k ) & 1) == 1