[英]How to Multiply a Floating Point Number using Bitwise Operators Without the Multiplication Operator in C
在 C 中,我得到一個 int x
並且必須僅使用以下按位和邏輯運算符將x
乘以 2: << >> ~ | ^ &
<< >> ~ | ^ &
. 運算符+ and *
是特別禁止的。
這通常很容易,因為我可以做x << 1
。 然而,這個問題的目標是假設 x 包含一個單精度float
值。
我相信假裝x
是一個float
是挑戰我們思考浮點數以及如何通過應用前面提到的移位和邏輯運算符來正確地乘以它們。
當談到移動浮點值時,我目前的理解是浮點數在移動時可能會被錯誤表示。 這樣對嗎? 如果不是,為什么? 否則,我的理解是正確的,並且我被困在如何實現這一點上。 任何幫助將不勝感激!
您需要將指數增加 1 才能將浮點值加倍。 這可以通過紋波進位加法器來完成:
#include <stdio.h>
#include <stdint.h>
int main()
{
float f = 3.14f ; // Test value
uint32_t* x = (int*)(&f) ; // get "bits view" of test value
// increment exponent
uint32_t mask = 0x00800000 ;
*x ^= mask ;
while( (*x & mask) == 0 &&
mask != 0x80000000 )
{
mask <<= 1 ;
*x ^= mask ;
}
// Show result
printf( "%f", f ) ;
return 0;
}
上面代碼的輸出是:
6.280000
該解決方案不處理指數溢出 - 這將需要尾數調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.