Help me programmers!

Status
Not open for further replies.

BenB

Ars Scholae Palatinae
1,136
I have to write a little funtion in Java for my computer architecture class that takes an integer and manually converts it to an 32-Bit IEEE floating point number.

I understand how to do all the bit manipulation. I know how to get the sign bit and the mantissa. I just don't know the algorithm for figuring out what the exponent bits should be.

If someone knows that algorithm it would be great if you could explain it to me.

Thanks in advance!
Ben
 
Not sure if this will help.... but I'd think the exponent should be log(abs(x)) (in base 10, where x is the integer you want to convert). You just floor this to the nearest integer.
Example:
12345, log(12345) = 4.09, floor(4.09) = 4, so you get 1.2345e4
0.0056, log(0.0056) = -2.25, floor(-2.25) = -3, you get 5.6e-3

The same thing should work with most numbers. Be careful with 0 though.
 

BenB

Ars Scholae Palatinae
1,136
I finally figured it out... here's the code if anyone is interested. It seems to work right.

code:<HR>
Code:
        public static float itof(int num) {
          int exponent = 0;
          int lastBit = 0x80000000;
          int checkBit = 0;
          int result = 0x00000000;
          
          /** Special case num == 0 */
          if (num == 0) {
             return Float.intBitsToFloat(0x00000000);
          }
          /** If number is negitive */
          if (num < 0) {
             /** Special case num == 2^-31 */
             if (num == 0xFFFFFFFF) {
                return Float.intBitsToFloat(0xd0000000);
             }
             /** inverse 2's compliment form */   
             num = -num;<P>             /** Find exponent */
             while (checkBit == 0 && exponent < 32) {
                checkBit = num & lastBit;
                num = num << 1;
                exponent++;
             }<P>             /** Normalize mantissa */
             exponent = (32 - exponent) +  127;
             exponent = exponent << 23;
             num = num >>> 9;<P>             /** Create bits for float */
             result = num | exponent | 0x80000000;
          }
          else {
             /** Num is positive */
             if (num > 0) {
                /** Find exponent */
                while (checkBit == 0 && exponent < 32) {
                   //System.out.println(exponent);
                   checkBit = num & lastBit;
                   num = num << 1;
                   exponent++;
                } <P>                /** Normalize mantissa */
                exponent = (32 - exponent) +  127;
                exponent = exponent << 23;
                num = num >>> 9;<P>                /** Create bits for float */
                result = num | exponent;
             }
          }
          return Float.intBitsToFloat(result);
       }

-Ben
 
Status
Not open for further replies.