简体   繁体   English

浮点数的按位乘法

[英]Bitwise multiplication of a floating point number

I am working on a project for school that requires me to manipulate floating point numbers using only their binary representation, specifically multiplying a float by two. 我正在为学校设计一个项目,该项目要求我仅使用浮点数的二进制表示来操纵浮点数,特别是将浮点数乘以2。 I am supposed to replicate the function of the following code using only bit operations (! | ^ & ~), logical operators (&&, ||), and if/while expressions. 我应该仅使用位运算(!| ^&〜),逻辑运算符(&&,||)和if / while表达式来复制以下代码的功能。

However, I am having a problem with some of my numbers not having the correct result. 但是,我有一些数字不正确的问题。 For example, when I pass in 8388608 (0x800000), the output is 8388608 when it should be 16777216 (0x1000000). 例如,当我传入8388608(0x800000)时,输出为8388608,而为16777216(0x1000000)。

Here is the code whose function we are supposed to replicate: 这是我们应该复制其功能的代码:

unsigned test_dl23(unsigned uf) {
float f = u2f(uf);
float tf = 2*f;
if (isnan(f))
  return uf;
else
  return f2u(tf);
}

And here is my attempt: 这是我的尝试:

unsigned dl23(unsigned uf) {

int pullExpMask, expMask, mantMask, i, mask, signedBit
mask = 0x007fffff;

pullExpMask = (-1 << 23) ^ 0x80000000; // fills lower 23 bits with zeroes
signedBit = 0x80000000 & uf;
expMask = (uf & pullExpMask); // grabs the exponent and signed bits, mantissa bits are zeroes
mantMask = mask & uf;

if (!(uf & mask)){ // if uf has an exponent that is all ones, return uf
    return uf;
}

else if (expMask == 0){
   mantMask =  mantMask << 1;

} 
else if (expMask != 0){
  expMask = expMask + 0x00100000;
}

return (signedBit | expMask | mantMask);


}

I have been working on this problem for a long time, and any helpful tips would be greatly appreciated! 我已经在这个问题上研究了很长时间了,任何有用的提示将不胜感激!

I'm not sure about what numbers you are referring to as failing, but I do see a bug in your code that would cause this behavior. 我不确定您指的是什么数字失败,但是我确实在您的代码中看到了一个会导致这种现象的错误。 The section with the comment // if uf has an exponent that is all ones, return uf does not do what this describes. // if uf has an exponent that is all ones, return uf带有注释的部分// if uf has an exponent that is all ones, return uf不会执行此操作。 It will test that the mantissa part is 0 and return the unchanged number, causing the behavior you're seeing. 它将测试尾数部分是否为0并返回未更改的数字,从而导致您看到的行为。 It should probably be something like if (expMask == pullExpMask) { 它可能应该类似于if (expMask == pullExpMask) {

Also, you need to consider the case that the exponent increment makes it all 1. It should always become an inf, and never a quiet or signaling NaN. 此外,您还需要考虑指数增量使其全部为1的情况。它应始终为inf,并且永远不要安静或发信号通知NaN。

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

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