Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I left-pad the string representation of a float?

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.

like image 638
apalopohapa Avatar asked Nov 17 '25 00:11

apalopohapa


1 Answers

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.

like image 140
Joey Avatar answered Nov 19 '25 15:11

Joey