# Write a program that converts floating-point numbers to/from decimal representation to Hex/Binary representations.

• May 13th, 2013, 01:35 PM
jenta
Write a program that converts floating-point numbers to/from decimal representation to Hex/Binary representations.
I am a writing a program to converts floating-point numbers to/from decimal representation to Hex/Binary representations. We have to do a setup which I already did, and now I have to figure out how to convert. I started out by trying to convert from hex to float first. I only got this far:
Code Java:

``` System.out.println("Enter Hex you want to convert"); String hex = input.nextLine(); int i = Integer.parseInt(hex); String by = Integer.toBinaryString(i); System.out.println("This is Binary: " + by); String expo = by.substring(0, exponent); String frac = by.substring(exponent+1);```
My problem is that the toBinaryString deletes leading 0's, so that my sign-bit and other leading zeros are lost. I also don't really know how to move on from this. Is there any way to convert hex to binary without loosing the leading zeros?

I am sorry if I posted this in the wrong place, or the wrong way, this is my first post here.
• May 13th, 2013, 05:09 PM
jenta
Re: Write a program that converts floating-point numbers to/from decimal representation to Hex/Binary representations.
Same poster again, I figured out how to go from hex to decimal floating point, but I can't go the opposite way. How do I go from decimal 8.5 to a hex representation of that floating point in java? I know how to do it on paper, but I can't figure out how to code it. 8.5 is 1000.1 in binary, how do I code that in java? And also, how do I move on from that?

Code Java:

``` System.out.println("Enter Float you want to convert: "); String f = input.nextLine(); double de = Double.parseDouble(f); String binFl = Long.toBinaryString(Double.doubleToRawLongBits(de)); System.out.println(binFl);```
I feel like what I am doing is completely wrong. I can't figure out how to go from a double to binary.