Golang BCD码和string互转
代码语言:javascript
复制package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
TestBcd2Number()
}
func TestBcd2Number() {
bcd := Hex2Byte("ffff1012")
fmt.Printf("bcd: %xn", bcd)
number := Bcd2Number(bcd)
fmt.Printf("bcd2number: %vn", number)
b := Number2bcd(number)
fmt.Printf("number2bcd: %xn", b)
}
func Bcd2Number(bcd []byte) string {
var number string
for _, i := range bcd {
number = fmt.Sprintf("X", i)
}
pos := strings.LastIndex(number,"F")
if pos == 8 {
return "0"
}
return number[pos 1:]
}
func Number2bcd(number string) []byte {
var rNumber = number
for i := 0; i < 8 - len(number); i {
rNumber = "f" rNumber
}
bcd := Hex2Byte(rNumber)
return bcd
}
func Hex2Byte(str string) []byte {
slen := len(str)
bHex := make([]byte, len(str)/2)
ii := 0
for i := 0; i < len(str); i = i 2 {
if slen != 1 {
ss := string(str[i]) string(str[i 1])
bt, _ := strconv.ParseInt(ss, 16, 32)
bHex[ii] = byte(bt)
ii = ii 1
slen = slen - 2
}
}
return bHex
}
运行结果: