Float calculation circuit (ry-No. 1.1 (float value in hexadecimal notation)

Get the hexadecimal notation of floating point numbers (SW)

Last time About Verilog-HDL implementation of Float calculation circuit-Part 1

4/26 Added simulation results 5/17 Fixed a negative number bug

Contents of this time

Is 32bit float (single) the correct value? Create a tool to convert between float value and hexadecimal notation value

use cgo

Great pioneer (references)

Let's get the internal representation of floating point numbers

Whole code

Code created this time

check.go


package main

/*
union {float f; unsigned i;} uv;

int f2b(float inp) {
	uv.f = inp;
	return uv.i;
}

float b2f(unsigned inp) {
	uv.i = inp;
	return uv.f;
}
*/
import "C"
import (
	"fmt"
	"os"
	"strconv"
)

func main() {
	if os.Args[1] == "f" {
		fmt.Println("float -> hx")
		fv, _ := strconv.ParseFloat(os.Args[2], 32)
		f2h(float32(fv))
	} else if os.Args[1] == "h" {
		fmt.Println("hx -> float")
		hv, _ := strconv.ParseUint(os.Args[2], 16, 32)
		h2f(uint(hv))
	}
}

func h2f(inp uint) {
	float := float32(C.b2f(_Ctype_uint(inp)))
	fmt.Println(float)
}

func f2h(inp float32) {
	bits := int(C.f2b(_Ctype_float(inp)))

	fmt.Printf("Hex:%08X\n", bits)
	fmt.Printf("Exp:%02X\n", bits >> 23 & 0xFF)
	fmt.Printf("Fra:%X\n", bits & 0x7FFFFF)
}

Converting values in a union

I don't do anything special, so I think it can be implemented in C as well. (Rather, can it be implemented only with Go?)

test

$ go run check.go f 7.25
float -> hx
Hex:40E80000
Exp:81
Fra:680000

Exp bias value 127 is 7F The value of the exponent part is 81, which is +2.

Also, since 680000 = 110 1000 0 0 0 0 You can see that 7.25 = 111.01 = 680000 x 2 ^ 2

$ go run check.go h 40E80000
hx -> float
7.25

You can see that it can be returned correctly

Verification of simulation results

7.25 + 11.625

7.25 + 11.625 = 18.875 \\
-> 40E8\_0000 + 413A\_0000 = 4197\_0000\\ 

Screenshot from 2020-04-26 20-05-25.png

It looks like it's right

12.345 + 3.1415926

12.345 + 3.1415926 = 15.4865926\\
-> 4145\_851F + 4049\_0FDA = 4177\_C915

Screenshot from 2020-04-26 20-09-04.png

It looks like it's right

Recommended Posts

Float calculation circuit (ry-No. 1.1 (float value in hexadecimal notation)
[python] Method to darken RGB value in hexadecimal notation
Shapley value calculation in Python
Convert exponential notation float to str in Python