Converts the specified float into its hexadecimal string representation. @param f the float to convert. @return the hexadecimal string representation of f. @since 1.5
(float f)
| 396 | * @since 1.5 |
| 397 | */ |
| 398 | public static String toHexString(float f) { |
| 399 | /* |
| 400 | * Reference: http://en.wikipedia.org/wiki/IEEE_754 |
| 401 | */ |
| 402 | if (f != f) { |
| 403 | return "NaN"; //$NON-NLS-1$ |
| 404 | } |
| 405 | if (f == POSITIVE_INFINITY) { |
| 406 | return "Infinity"; //$NON-NLS-1$ |
| 407 | } |
| 408 | if (f == NEGATIVE_INFINITY) { |
| 409 | return "-Infinity"; //$NON-NLS-1$ |
| 410 | } |
| 411 | |
| 412 | int bitValue = floatToIntBits(f); |
| 413 | |
| 414 | boolean negative = (bitValue & 0x80000000) != 0; |
| 415 | // mask exponent bits and shift down |
| 416 | int exponent = (bitValue & 0x7f800000) >>> 23; |
| 417 | // mask significand bits and shift up |
| 418 | // significand is 23-bits, so we shift to treat it like 24-bits |
| 419 | int significand = (bitValue & 0x007FFFFF) << 1; |
| 420 | |
| 421 | if (exponent == 0 && significand == 0) { |
| 422 | return (negative ? "-0x0.0p0" : "0x0.0p0"); //$NON-NLS-1$ //$NON-NLS-2$ |
| 423 | } |
| 424 | |
| 425 | StringBuilder hexString = new StringBuilder(10); |
| 426 | if (negative) { |
| 427 | hexString.append("-0x"); //$NON-NLS-1$ |
| 428 | } else { |
| 429 | hexString.append("0x"); //$NON-NLS-1$ |
| 430 | } |
| 431 | |
| 432 | if (exponent == 0) { // denormal (subnormal) value |
| 433 | hexString.append("0."); //$NON-NLS-1$ |
| 434 | // significand is 23-bits, so there can be 6 hex digits |
| 435 | int fractionDigits = 6; |
| 436 | // remove trailing hex zeros, so Integer.toHexString() won't print |
| 437 | // them |
| 438 | while ((significand != 0) && ((significand & 0xF) == 0)) { |
| 439 | significand >>>= 4; |
| 440 | fractionDigits--; |
| 441 | } |
| 442 | // this assumes Integer.toHexString() returns lowercase characters |
| 443 | String hexSignificand = Integer.toHexString(significand); |
| 444 | |
| 445 | // if there are digits left, then insert some '0' chars first |
| 446 | if (significand != 0 && fractionDigits > hexSignificand.length()) { |
| 447 | int digitDiff = fractionDigits - hexSignificand.length(); |
| 448 | while (digitDiff-- != 0) { |
| 449 | hexString.append('0'); |
| 450 | } |
| 451 | } |
| 452 | hexString.append(hexSignificand); |
| 453 | hexString.append("p-126"); //$NON-NLS-1$ |
| 454 | } else { // normal value |
| 455 | hexString.append("1."); //$NON-NLS-1$ |
nothing calls this directly
no test coverage detected