2019-11-06 13:51:29 +00:00
|
|
|
package sii
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/binary"
|
|
|
|
"encoding/hex"
|
2019-12-10 22:20:25 +00:00
|
|
|
"fmt"
|
|
|
|
"math"
|
2019-11-06 13:51:29 +00:00
|
|
|
"strconv"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
func float2sii(f float32) ([]byte, error) {
|
|
|
|
var (
|
|
|
|
buf = new(bytes.Buffer)
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
2019-12-11 17:38:05 +00:00
|
|
|
if math.Floor(float64(f)) == float64(f) && f < 1000 && f > -1000 {
|
2019-12-10 22:20:25 +00:00
|
|
|
return []byte(fmt.Sprintf("%.0f", f)), nil
|
|
|
|
}
|
|
|
|
|
2019-11-06 13:51:29 +00:00
|
|
|
err = binary.Write(buf, binary.BigEndian, f)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "Unable to encode float")
|
|
|
|
}
|
|
|
|
|
|
|
|
dst := make([]byte, hex.EncodedLen(buf.Len()))
|
|
|
|
hex.Encode(dst, buf.Bytes())
|
|
|
|
|
|
|
|
return append([]byte("&"), dst...), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func sii2float(f []byte) (float32, error) {
|
2019-12-24 14:00:16 +00:00
|
|
|
if len(f) == 0 {
|
|
|
|
return 0, nil
|
|
|
|
}
|
|
|
|
|
2019-11-06 13:51:29 +00:00
|
|
|
if f[0] != '&' {
|
|
|
|
out, err := strconv.ParseFloat(string(f), 32)
|
|
|
|
return float32(out), err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Strip leading '&'
|
|
|
|
f = f[1:]
|
|
|
|
|
|
|
|
var (
|
|
|
|
err error
|
|
|
|
out float32
|
|
|
|
)
|
|
|
|
|
|
|
|
dst := make([]byte, hex.DecodedLen(len(f)))
|
|
|
|
_, err = hex.Decode(dst, f)
|
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrap(err, "Unable to read hex format")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = binary.Read(bytes.NewReader(dst), binary.BigEndian, &out)
|
|
|
|
return out, errors.Wrap(err, "Unable to decode hex notation")
|
|
|
|
}
|