Skip to content

Commit

Permalink
feat: add float parse lib function
Browse files Browse the repository at this point in the history
  • Loading branch information
wwhai committed Dec 15, 2022
1 parent 21c4b74 commit 6fe2876
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions engine/lua_runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ func LoadBuildInLuaLib(e typex.RuleX, r *typex.Rule) {
r.AddLib(e, "rulexlib", "BS2B", rulexlib.BitStringToBytes(e))
r.AddLib(e, "rulexlib", "HToN", rulexlib.HToN(e))
r.AddLib(e, "rulexlib", "HsubToN", rulexlib.HsubToN(e))
// 浮点数处理
r.AddLib(e, "rulexlib", "Bin2F32", rulexlib.BinToFloat32(e))
r.AddLib(e, "rulexlib", "Bin2F64", rulexlib.BinToFloat32(e))
// URL处理
r.AddLib(e, "rulexlib", "UrlBuild", rulexlib.UrlBuild(e))
r.AddLib(e, "rulexlib", "UrlBuildQS", rulexlib.UrlBuildQS(e))
Expand Down
36 changes: 36 additions & 0 deletions rulexlib/binary_lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/hex"
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -411,6 +412,11 @@ func ReverseString(text string) string {
return string(textRunes)
}

/*
*
* 字节逆序
*
*/
func reverse(runes []rune, length int) {
for i, j := 0, length-1; i < length/2; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
Expand Down Expand Up @@ -458,10 +464,40 @@ func HsubToN(rx typex.RuleX) func(*lua.LState) int {
}
}

/*
*
* 十六进制字符串转数字
*
*/
func HexToNumber(s string) (int64, error) {
iv, err := strconv.ParseInt(s, 16, len(s)*8)
if err != nil {
return 0, err
}
return iv, nil
}

/*
*
* 二进制转浮点数,参考资料:
* https://blog.51cto.com/u_12512821/2363818
* https://www.ruanyifeng.com/blog/2010/06/ieee_floating-point_representation.html
*
*/

func BinToFloat32(rx typex.RuleX) func(*lua.LState) int {
return func(l *lua.LState) int {
bin := l.ToString(2)
bits := binary.BigEndian.Uint32([]byte(bin))
l.Push(lua.LNumber(math.Float32frombits(bits)))
return 1
}
}
func BinToFloat64(rx typex.RuleX) func(*lua.LState) int {
return func(l *lua.LState) int {
bin := l.ToString(2)
bits := binary.BigEndian.Uint64([]byte(bin))
l.Push(lua.LNumber(math.Float64frombits(bits)))
return 1
}
}

0 comments on commit 6fe2876

Please sign in to comment.