-
Notifications
You must be signed in to change notification settings - Fork 54
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
138 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package cbor | ||
|
||
// float16: | ||
// sign|exp(5)|mant(10) | ||
// | ||
// float32: | ||
// sign|exp(8)|mant(23) | ||
func float16to32(f uint16) uint32 { | ||
sign, exp, mant := splitf16(f) | ||
if exp == 0x1f { | ||
return sign | 0xff<<23 | exp // infinity/NaN | ||
} | ||
|
||
if exp == 0 { | ||
if mant == 0 { // subnormal 0, but keep the exponent | ||
return sign | (exp+127-15)<<23 | ||
} | ||
|
||
// this is a float16 subnormal (true exponent -14) | ||
// starting from there, we shift the mantissa over until we've | ||
// chopped off the most-significant 1, i.e. that becomes the hidden | ||
// mantissa bit and we're back in normal float32 space | ||
exp = -14 + 127 | ||
for mant&0x800000 == 0 { // repeat until bit 24 is 1 | ||
mant <<= 1 | ||
exp-- | ||
} | ||
mant &= 0x7FFFFF // remask to 23bit | ||
} else { | ||
exp += 127 - 15 | ||
} | ||
|
||
return sign | exp<<23 | mant | ||
} | ||
|
||
// breaks a float16 down into its components: | ||
// - sign, in float32 position | ||
// - exponent, as a number (for bias shifting and subnormal conversion) | ||
// - mantissa, in float32 position | ||
func splitf16(f uint16) (sign, exp, mantissa uint32) { | ||
const smask = 0b_1 << 15 | ||
const emask = 0b_11111 << 10 | ||
const mmask = 0b_1111111111 | ||
|
||
return uint32(f&smask) << 16, uint32(f&emask) >> 10, uint32(f&mmask) << 13 | ||
} |