【发布时间】:2012-10-03 21:51:31
【问题描述】:
我正在尝试完成一项要求我为二进制算术编写三个函数的作业。 badd() 是为我提供的,所以我用它来帮助编写 bsub() 和 bmult() 函数。但是,我无法理解应该如何执行 bdiv() 函数。我知道我需要使用右移和我的 bsubb() 函数来遍历这些位,但我不知道如何实现它。以下是我到目前为止编写的函数。如果您注意到我在编写它们时犯的任何错误(意思是 bsub() 和 bmult()),请告诉我。谢谢。
/** This function adds the two arguments using bitwise operators. Your
* implementation should not use arithmetic operators except for loop
* control. Integers are 32 bits long. This function prints a message
* saying "Overflow occurred\n" if a two's complement overflow occurs
* during the addition process. The sum is returned as the value of
* the function.
*/
int badd(int x,int y){
int i;
char sum;
char car_in=0;
char car_out;
char a,b;
unsigned int mask=0x00000001;
int result=0;
for(i=0;i<32;i++){
a=(x&mask)!=0;
b=(y&mask)!=0;
car_out=car_in & (a|b) |a&b;
sum=a^b^car_in;
if(sum) {
result|=mask;
}
if(i!=31) {
car_in=car_out;
} else {
if(car_in!=car_out) {
printf("Overflow occurred\n");
}
}
mask<<=1;
}
return result;
}
// subracts two integers by finding the compliemnt
// of "y", adding 1, and using the badd() function
// to add "-y" and "x"
int bsub(int x, int y){
return badd(x, badd(~y, 1));
}
//add x to total for however many y
int bmult(int x,int y){
int total;
int i;
for(i=0; i < = y; i++)
{
total = badd(total,x)
}
return total;
}
// comment me
unsigned int bdiv(unsigned int dividend, unsigned int divisor){
// write me
return 0;
}
【问题讨论】:
-
看起来你必须结合乘法和减法来计算商和提醒,通过解决this simple equation
-
根据homework guidelines 的说法,这个问题太做作了,不是一个实用的编程问题,应该作为 Not a Real Question 结束。
标签: c assembly bit-manipulation division