Skip to content

Instantly share code, notes, and snippets.

@eric-unc
Last active May 3, 2020 02:23
Show Gist options
  • Select an option

  • Save eric-unc/153b2a900b643b65f0c84f04a9a71413 to your computer and use it in GitHub Desktop.

Select an option

Save eric-unc/153b2a900b643b65f0c84f04a9a71413 to your computer and use it in GitHub Desktop.
// This program will convert a "minifloat" in the format of 8 bits into decimal representation, assuming a -3 exponent bias.
// For example, this will convert 01011001 to 6.25.
// THIS PROGRAM DOES NOT COVER SPECIAL CASES! I'm too lazy to add this, I spent enough time making this already.
// Author: Eric Schneider
package main
import (
"bufio"
"fmt"
"math"
"os"
"regexp"
)
func main(){
reader := bufio.NewReader(os.Stdin)
expression := regexp.MustCompile(`([01])([01]{3})([01]{4})`)
for {
fmt.Println("Enter your minifloat. If it isn't a minifloat, then the program will exit.")
text, _ := reader.ReadString('\n')
results := expression.FindStringSubmatch(text)
if results == nil {
break;
}
sign := get_sign(results[1])
expobits := get_expobits(results[2])
sigbits := get_sigbits(results[3])
result := sign * expobits * sigbits
fmt.Print(":")
fmt.Println(result)
fmt.Println()
}
}
func get_sign(bit string) float64 {
if bit == "0" {
return 1
} else {
return -1
}
}
func get_expobits(bits string) float64 {
length := len(bits)
ret := 0
for i := 0; i < length; i++ {
if bits[i] == '1' {
ret += int(math.Pow(2, float64(i)))
}
}
return math.Pow(2, float64(ret - 3))
}
func get_sigbits(bits string) float64 {
length := len(bits)
ret := 1.0
for i := 0; i < length; i++ {
if bits[i] == '1' {
ret += math.Pow(2, float64(-1 * (i + 1)))
}
}
return ret
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment