gpt4 book ai didi

c - 实现 Booth 算法时的位移位和类型转换问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:03 25 4
gpt4 key购买 nike

我正在编写一个实现 Booth's Algorithm 的程序乘以整数。我只被允许使用位级运算符、逻辑运算符和位移位。我允许程序有一个循环,以及一个将添加两个整数的函数。我无法理解我的程序出了什么问题。当我使用按位运算符来屏蔽 long long 的一半时,我得到了不正确的值。关于我在那里做错了什么的任何建议?也许我不明白如何正确掩饰。它也可能与类型转换有关;我真的不确定。在此先感谢您的帮助!

代码如下:

#include <stdio.h>

int Add (int x, int y);
long long Booth (int x, int y);

int main() {
int hex1, hex2;
long long product;
printf("\nEnter Multiplicand & Multiplier in hex: ");
scanf(" %x %x", &hex1, &hex2);

product = Booth(hex1, hex2);

printf("Multiplicand = 0x%08X \tAs signed = %+d\n", hex1, hex1);
printf("Multiplier = 0x%08X \tAs signed = %+d\n", hex2, hex2);
printf("Product = 0x%16X \tAs signed = %+d\n", product, product);
}

int Add (int x, int y) {
return x + y;
}

long long Booth (int multiplicand, int multiplier) {
int i;
long long product;
long long productLH;
long long productRH;
int productLHI;
int productRHI;
int cOut;
int negMultiplicand;
negMultiplicand = Add (~multiplicand, 1);
product = (long long) Add (0, multiplier);

for (i = 0; i < 32; i++) {
if (((product & 1) == 1) && (cOut == 0)) {
//Mask left half and right half of product
productLH = (product & 0xFFFFFFFF00000000);
productRH = (product & 0x00000000FFFFFFFF);

//Bit shift product so all values are in lower 32 bits
productLH = (productLH >> 32);

//Convert left halves and right halves to ints
productLHI = (int) (productLH & 0x00000000FFFFFFFF);
productRHI = (int) productRH & (0x00000000FFFFFFFF);
productLHI = Add(productLHI, negMultiplicand);

//Put halves back together
product = (long long) Add(productLHI, 0);
product = ((product << 32) & 0xFFFFFFFFFFFFFFFF);
product = (long long) Add((int)product, productRHI);
}
else if (((product & 1) == 0) && (cOut == 1)) {
//Mask left half and right half of product
productLH = (product & 0xFFFFFFFF00000000);
productRH = (product & 0x00000000FFFFFFFF);

//Bit shift product so all values are in lower 32 bits
productLH = (productLH >> 32);

//Convert left halves and right halves to ints
productLHI = (int) (productLH & 0x00000000FFFFFFFF);
productRHI = (int) productRH & (0x00000000FFFFFFFF);
productLHI = Add(productLHI, multiplicand);

//Put halves back together
product = (long long) Add(productLHI, 0);
product = ((product << 32) & 0xFFFFFFFFFFFFFFFF);
product = (long long) Add((int)product, productRHI);
}
cOut = (product & 1);
product = product >> 1;
}
return product;
}

最佳答案

函数 Add() 的返回值可能不是整数类型,但您返回的是 int 类型。如果我们将两个整数相加可能会得到多个 int 类型。

关于c - 实现 Booth 算法时的位移位和类型转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35447511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com