如何左键填充浮点数的字符串表示?

apa*_*apa 3 java floating-point integer padding

我正在尝试将单个精度浮点数转换为四个字节的ascii表示(sign/exponent/mantissa).我目前的代码是:

Integer.toString(Float.floatToRawIntBits(f),16);
Run Code Online (Sandbox Code Playgroud)

Float.floatToRawIntBits使用相同的字节Integer.toString生成一个整数,然后以十六进制形式创建ascii数字(因此指定了radix = 16).我的问题是我总是需要8个ascii字符加上可选的' - '符号,而Integer.toString不是左边的零填充.

任何人都能想出一个优雅的解决方案吗?

谢谢.

Joe*_*oey 8

您可以使用String.format():

String.format("%08x", Float.floatToRawIntBits(f))
Run Code Online (Sandbox Code Playgroud)

这将对结果进行零填充并将其格式化为十六进制数.格式字符串的详细信息可以在这里找到.