Converting Float Base-10 value to Base 2/8/16, then to Bytes

I’m trying to convert a float number from base10 to base2/8/16, then convert it to bytes (base256) of the converted values, by far I can do it mathematically like:

0.15625 (base 10) = 0.00101 (base2) = 101 x 2^-5 (base2)  --> 0x00 (positive sign), 0x05 (mantissa), 0xFB (exponent)
0.15625 (base 10) = 0.12 (base8) = 12 x 8^-2 (base8) --> 0x00 (positive sign), 0x0c (mantissa), 0xFE (exponent)
-0.15625 (base 10) = -0.00101 (base2) = -101 x 2^-5 (base2)  --> 0xFF (negative sign), 0x05 (mantissa), 0xFB (exponent)
-0.15625 (base 10) = -0.12 (base8) = -12 x 8^-2 (base8) --> 0xFF (negative sign), 0x0c (mantissa), 0xFE (exponent)

Is there an existing library that can convert float32, float64, or big.Float from math package to the desired output or do I have to create the library on my own?

The mathematical conversion involves a lot of division in the mathematical world and I heard it can strain the CPU with too many division operations.

1 Like

In case anyone is interested how did 0.15625 (base 10) becomes 0.00101 (base2), here is the link for conversion.

  1. https://binary-system.base-conversion.ro/real-number-converted-from-decimal-system-to-32bit-single-precision-IEEE754-binary-floating-point.php?decimal_number_base_ten=12.375&sign=0&exponent=10000010&mantissa=10001100000000000000000
1 Like

On the safe side, I’m afraid you need to create your own encoding package.

big.Float is not going to help much in base number conversion apart from holding large numbers while math package only offers exp2 functionality. Both accuracy can be different, case-by-case basis.

You can do a code reference for the exponent base conversion: - The Go Programming Language

Another good option to refer spektre’s algorithm for base conversion. Link: java - Converting base of floating point number without losing precision - Stack Overflow

1 Like

Noted with thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.