简体   繁体   English

将Pascal的“ shr”转换为C的“ >>”

[英]Converting Pascal's “shr” to C's “>>”

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'. 我在将一些Pascal代码转换为C时遇到问题。基本上,我有嵌套循环,其中循环递增“ k”在循环递增“ i”之内。 In both cases, I want to execute the command "if i (right shifted by) k AND 1 = 1, then do the following {code}". 在这两种情况下,我都想执行命令“如果i(右移)k AND 1 = 1,则执行以下{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 CI have: 我已经从Pascal代码中绘制了数据,它是正确的,因此我假设此算法是我要在C中复制的算法。在CI中具有:

/*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. 在调试这些行时,我正在写文件,以显示Pascal的“ i shr k”和C的“ i >> k”的值。 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: 我对“ i >> k”的C结果是:

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. 我还发现,在Pascal版本中,对于给定的i值,“ if”语句内部的访问次数更多。 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? 我知道Pascal的“ shr”是逻辑移位,C的“ >>”是算术移位,但是我认为将(unsigned int)类型转换放在“ >>”的左操作数前面会解决这个问题吗? Anybody have any advice on how to make my C statement equivalent to the Pascal statement? 有人对如何使我的C语句等同于Pascal语句有任何建议吗? It would be very much appreciated ! 非常感谢!

Thanks for reading! 谢谢阅读!

Your problem appears to be with operator precedance. 您的问题似乎与操作员优先有关。

In the Pascal version, your condition is this: 在Pascal版本中,您的条件是这样的:

((i shr k) and 1)=1

In the C version, your condition is this (with some brackets added to show precedance): 在C版本中,您的条件是这样(添加了一些括号以显示优先顺序):

(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM