我想轉換存儲爲int的十六進制值並將它們轉換爲使用IEEE 32位規則的浮點數。我特別努力爲尾數和指數獲得正確的值。十六進制以十六進制格式存儲在文件中。我想要有四位有意義的人物。以下是我的代碼。如何將十六進制轉換爲IEEE 754 32位浮點C++
float floatizeMe(unsigned int myNumba) {
//// myNumba comes in as 32 bits or 8 byte
unsigned int sign = (myNumba & 0x007fffff) >>31;
unsigned int exponent = ((myNumba & 0x7f800000) >> 23)- 0x7F;
unsigned int mantissa = (myNumba & 0x007fffff) ;
float value = 0;
float mantissa2;
cout << endl<< "mantissa is : " << dec << mantissa << endl;
unsigned int m1 = mantissa & 0x00400000 >> 23;
unsigned int m2 = mantissa & 0x00200000 >> 22;
unsigned int m3 = mantissa & 0x00080000 >> 21;
unsigned int m4 = mantissa & 0x00040000 >> 20;
mantissa2 = m1 * (2^-1) + m2*(2^-2) + m3*(2^-3) + m4*(2^-4);
cout << "\nsign is: " << dec << sign << endl;
cout << "exponent is : " << dec << exponent << endl;
cout << "mantissa 2 is : " << dec << mantissa2 << endl;
// if above this number it is negative
if (sign == 1)
sign = -1;
// if above this number it is positive
else {
sign = 1;
}
value = (-1^sign) * (1+mantissa2) * (2^exponent);
cout << dec << "Float value is: " << value << "\n\n\n";
return value;
}
int main()
{
ifstream myfile("input.txt");
if (myfile.is_open())
{
unsigned int a, b,b1; // Hex
float c, d, e; // Dec
int choice;
unsigned int ex1 = 0;
unsigned int ex2 = 1;
myfile >> std::hex;
myfile >> a >> b ;
floatizeMe(a);
myfile.close();
return 0;
}
'2^-1'(等等)應該計算什麼? – usr2564301
您的'sign'位總是0. – usr2564301
如果您嘗試將**轉換爲** IEEE 754 32位,那麼輸入的表示是什麼? – user2079303