计算32位数字数组的奇数个位中有多少个1 [英] Count how many 1 there are in the odd positions of an array of 32-bit numbers

查看:258
本文介绍了计算32位数字数组的奇数个位中有多少个1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个简单的汇编函数,该函数通过c中的程序调用,以32位为单位计算数组的奇数位置有1个.传递给函数的第一个参数是指向数组的指针,第二个参数是元素的数量.我不知道它会进入无限循环.

I'm implementing a simple assembly function called through a program in c, to count how many 1 there are in the odd position of an array in 32 bits. The first argument passed to the function is the pointer to the array while the second the number of elements. I do not understand what it does go to infinite loop.

//汇编代码

.globl ones_in_odds
.type ones_in_odds,@function

ones_in_odds:
pushl %ebp
movl %esp,%ebp

movl 8(%ebp),%ecx
movl 12(%ebp),%esi

#xorl %edi,%edi
xorl %eax,%eax
subl $-1,%esi

startloop:
cmpl $0,%esi
jl endloop
movl (%ecx,%esi,4),%edx
xorl %edi,%edi

innerloop:
cmpl $16,%edi
jg startloop
shrl %edx
shrl %edx
adcl $00,%eax
incl %edi
jmp innerloop

decl %esi
jmp startloop

endloop:
movl %ebp,%esp
popl %ebp
ret

//C代码

#include <stdio.h>
#define DIM 5

int ones_in_odds(int *,size_t);

int main(){

int array[DIM] = {1,3,4,5,6};
int one = ones_in_odds(array,DIM);
printf("Il numero di 1 nelle posizioni dispari e' %d\n",one);
return 0;
}

推荐答案

向添加 1:

This adds 1 to ESI:

subl $-1,%esi

就像术语ESI = ESI - (-1).您想要将项目(DIM)的 count 转换为array中最后一个项目的 index .因此,必须将计数减1或加(-1).但是,您不需要在此进行此转换.删除行.

It's like the term ESI = ESI - (-1). You want to transform the count of items (DIM) to the index of the last item in array. Thus the count has to be subtracted by 1 or added by (-1). However, you don't need this transformation at this place. Remove the line.

由于

jg startloop

您没有达到decl %esi,因此中断条件jl endloop将永远不会得到满足.

you don't reach decl %esi and therefore the break condition jl endloop will never been met.

decl %esi移至startloop的开头,您还将解决上面的转换问题.

Move decl %esi to the beginning of startloop and you solve also the transformation problem above.

正如@Jester所述,您必须遵循 C调用约定,汇编过程是C程序的功能.允许该函数更改EAXECXEDX(保存调用者"),并且必须返回所有其他未更改的寄存器(保存被调用者").该函数会更改ESIEDI,但应保持不变.因此,将它们推入功能的开头,然后将其弹出.

As @Jester mentions, you have to follow the C calling convention since the assembly procedure is a function of the C program. The function is allowed to change EAX, ECX, and EDX ("caller saved") and has to return all other registers unchanged ("callee saved"). The function changes ESI and EDI, but should returm them unchanged. So push them at the beginning of the function and pop them at the end.

这篇关于计算32位数字数组的奇数个位中有多少个1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆