Skip to content

Instantly share code, notes, and snippets.

@igstan
Created August 6, 2024 20:12
Show Gist options
  • Save igstan/b795c0e6355db3e12b59309feb4f7b99 to your computer and use it in GitHub Desktop.
Save igstan/b795c0e6355db3e12b59309feb4f7b99 to your computer and use it in GitHub Desktop.
#!/usr/bin/env -S scala-cli shebang -S 3
/**
* https://www.doc.ic.ac.uk/~eedwards/compsys/float/
*/
import java.{ lang => j }
val n = args(0).toFloat
val bits = j.Float.floatToRawIntBits(n)
val sign = (bits >> 31) & 0x1
val exponent = (bits >> 23) & 0xFF
val mantissa = (bits & 0x7FFFFF) | 0x800000
val digits = "%s %s %s".format(
j.Integer.toBinaryString(sign),
j.Integer.toBinaryString(exponent | 0x100).drop(1),
j.Integer.toBinaryString(mantissa).drop(1),
)
val exponentS = exponent - 127
val mantissaS = j.Integer.parseUnsignedInt(mantissa.toBinaryString.reverse, 2)
println(s"IEEE-754 representation for single precision number: ${n}f")
println(s"")
println(s" $digits")
println(s" └┬┴───┬────┴───────────┬───────────┘")
println(s" │ │ │")
println(s" └────│────────────────│─────────── sign: ${ if (sign == 0) "+" else "-" }")
println(s" └────────────────│─────────── exponent: $exponentS")
println(s" └─────────── mantissa: $mantissaS")
println(s"")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment