开发者

Given IEEE binary representation of a real how to get its true binary representation in Java?

开发者 https://www.devze.com 2023-04-10 11:08 出处:网络
I am just wonder how to use bit operations to achieve the goal: given an IEEE binary representation of 开发者_JAVA百科a real, for example, 40AC0000 (5.375 in decimal), how to get its true binary repre

I am just wonder how to use bit operations to achieve the goal: given an IEEE binary representation of 开发者_JAVA百科a real, for example, 40AC0000 (5.375 in decimal), how to get its true binary representation (expecting 101.011 for the example) in Java?


This is kind of a tough question, especially if you don't already know about IEEE floats.

Since there are 4 bytes in your number, it's single precision. This means it has a structure of 1 sign bit, 8 Exponent bits and 23 Mantissa bits. The sign bit is obvious. The meaning of the exponent bits affects how you interpret the Mantissa bits. First check the 8 exponents bits. If they are all 0, you have a denormalized number; if they are all 1, you have an infinity value or a NaN; otherwise, it is normalized.

In the normalized , take the exponent bits, interpret it as an 8 bit number and subtract 127_10 (or 0xf7) from it. This is your exponent. Then take the remaining Mantissa bits, add a leading 1. Your result is then (-1)^[Sign] * 1.[Mantissa] * 2^[Exponent].

If it is a denormalized number, your exponent is -126 (1-127). In this case, interpret as (-1)^[Sign] * 0.[Mantissa] * 2^[Exponent].

In the remaining cases, if the Mantissa is all 0s, your number is (-1)^[Sign] * infinity. Otherwise, your float is a NaN.

Hope that helps.


Do you mean Float.floatToIntBits() and Float.intBitsToFloat() ?


What do you mean by "true binary representation"? There is nothing "untrue" about the hex representation (40AC0000).

You can convert between different radixes (hex, binary, decimal) using the methods on Integer:

Float.floatToIntBits(new Float("5.375"));
// = 1085014016

Integer.toString(1085014016, 16);
// = "40ac0000"

Integer.valueOf("40AC0000", 16);
// = 1085014016

Integer.toString(1085014016, 2); 
// returns 1000000101011000000000000000000
0

精彩评论

暂无评论...
验证码 换一张
取 消