Question

I'm trying to convert a single precision floating point number into an ascii representation of the four bytes that make it (sign/exponent/mantissa). My current code is:

Integer.toString(Float.floatToRawIntBits(f),16);

Float.floatToRawIntBits makes an integer using the same bytes, and then Integer.toString creates the ascii digits in hex form (hence the radix = 16 specified). My problem is that I always need 8 ascii characters plus the optional '-' sign, and Integer.toString is not padding with left side zeroes.

Can anybody come up with an elegant solution?

Thanks.

Was it helpful?

Solution

You can use String.format():

String.format("%08x", Float.floatToRawIntBits(f))

This will zero-pad the result and format it as a hexadecimal number. Details on format strings can be found here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top