views:

269

answers:

1

Hello. 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.

+7  A: 

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.

Joey
Elegant and perfectly functional. Thanks a lot!!
apalopohapa