Add: Float64 byte slice conversions
This commit is contained in:
parent
84d2f8bc95
commit
56c9b804e5
|
@ -15,17 +15,16 @@ var needle = []byte(entropy.RandStr(16))
|
|||
|
||||
func TestBlakeEqualAndB64(t *testing.T) {
|
||||
var clone = make([]byte, len(needle))
|
||||
for i, c := range needle {
|
||||
clone[i] = c
|
||||
}
|
||||
copy(clone, needle)
|
||||
|
||||
if !hash.BlakeEqual(needle, clone) {
|
||||
t.Fatalf("BlakeEqual failed! Values %v and %v should have been equal.\n|---->Lengths: %d and %d",
|
||||
needle, clone, len(needle), len(clone),
|
||||
)
|
||||
}
|
||||
clone = make([]byte, len(needle))
|
||||
clone = []byte(entropy.RandStr(16))
|
||||
if hash.BlakeEqual(needle, clone) {
|
||||
|
||||
falseclone := []byte(entropy.RandStr(16))
|
||||
if hash.BlakeEqual(needle, falseclone) {
|
||||
t.Fatalf("BlakeEqual failed! Values %v and %v should NOT have been equal.\n|---->Lengths: %d and %d",
|
||||
needle, clone, len(needle), len(clone),
|
||||
)
|
||||
|
@ -73,3 +72,16 @@ func TestAbs(t *testing.T) {
|
|||
t.Fatalf("Abs failed! values %d and %d should have been equal.", start, negged)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCruisinInMy64(t *testing.T) {
|
||||
data := 420.69
|
||||
databytes := Float64ToBytes(data)
|
||||
if len(databytes) < 1 {
|
||||
t.Fatalf("Float64ToBytes has returned a zero length value")
|
||||
}
|
||||
result := BytesToFloat64(databytes)
|
||||
if result != data {
|
||||
t.Fatalf("BytesToFloat64 failed! wanted %v and got %v", data, result)
|
||||
}
|
||||
t.Logf("original float64: %v -> Float64ToBytes %v -> BytesToFloat64 %v", data, databytes, result)
|
||||
}
|
||||
|
|
16
util.go
16
util.go
|
@ -1,8 +1,10 @@
|
|||
package common
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
@ -23,3 +25,17 @@ func Abs(n int) int {
|
|||
n64 = (n64 ^ y) - y
|
||||
return int(n64)
|
||||
}
|
||||
|
||||
// Float64ToBytes will take a float64 type and convert it to a slice of bytes.
|
||||
func Float64ToBytes(f float64) []byte {
|
||||
var buf [8]byte
|
||||
binary.LittleEndian.PutUint64(buf[:], math.Float64bits(f))
|
||||
return buf[:]
|
||||
}
|
||||
|
||||
// BytesToFloat64 will take a slice of bytes and convert it to a float64 type.
|
||||
func BytesToFloat64(bytes []byte) float64 {
|
||||
bits := binary.LittleEndian.Uint64(bytes)
|
||||
float := math.Float64frombits(bits)
|
||||
return float
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue