golang数据转换技巧

将uint32与byte[]互转

package main

import (
	"encoding/binary"
	"fmt"
)

func main() {
	// 一个长度为4的byte切片,表示一个负数
	bytes := []byte{0xFF, 0xFF, 0xFF, 0xFF}

	// 将byte切片转换为int32
	num := int32(binary.BigEndian.Uint32(bytes))
	fmt.Printf("Byte切片转换为Int32:%d\n", num)

	// 创建一个长度为4的byte切片
	ibytes := make([]byte, 4)

	// 将int32值写入byte切片中
	binary.BigEndian.PutUint32(ibytes, uint32(num))

	fmt.Printf("Int32写入Byte切片:%#v\n", ibytes)
}

在线运行效果 in https://go.dev/play/
image

json解析去除第一行不完整数据

    //首行数据不完整
	const jsonStream = `ft yourself!"}
	{"Name": "Ed", "Text": "Knock knock."}
	{"Name": "Sam", "Text": "Who's there?"}
	{"Name": "Ed", "Text": "Go fmt."}
	{"Name": "Sam", "Text": "Go fmt who?"}
	{"Name": "Ed", "Text": "Go fmt yourself!"}
`
	type Message struct {
		Name, Text string
	}

	strReader := strings.NewReader(data)
	bufReader := bufio.NewReader(strReader)
	_, _, err := bufReader.ReadLine()
	if err != nil {
		return
	}
	jdec := json.NewDecoder(bufReader)
	for {

		var m Message
		if err := jdec.Decode(&m); err == io.EOF {
			fmt.Println("EOF reached!")
			break
		} else if err != nil {
			fmt.Printf("decoded error: %+v\n", err)
			return
		}
		fmt.Printf("%+v\n", m)
	}
	

完整代码:

点击查看代码
package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"github.com/xluohome/serial"
	"io"
	"os"
	"strings"
)

var (
	Serial *SerialPort
)

const name = "COM1" //"/dev/ttyS1"

type SerialPort struct {
	Port *serial.Port
}

func (s *SerialPort) JsonDecoder() *json.Decoder {
	f, err := os.Open(name)
	if err != nil {
		fmt.Println("Serial port error: ", err)
	}
	reader := bufio.NewReader(f)
	return json.NewDecoder(reader)
}

type Message struct {
	//Time   string `json:"time"` // //10位十进制的unix时间戳
	Time int64 `json:"timestamp,string" ` // //10位十进制的unix时间戳
	Cat1 int   `json:"cat1,string"`
	Cat2 int   `json:"cat2,string"`
}

const data = `"}
{"timestamp":"6620727936541","cat1":"33580443","cat2":"4660"}
{"timestamp":"6620727936541","cat1":"33580443","cat2":"4660"}

`

func main() {

	test()

}

func test() {
	strReader := strings.NewReader(data)
	bufReader := bufio.NewReader(strReader)
	_, _, err := bufReader.ReadLine()
	if err != nil {
		return
	}
	jdec := json.NewDecoder(bufReader)
	jdec.DisallowUnknownFields()
	for {

		var m Message
		if err := jdec.Decode(&m); err == io.EOF {
			fmt.Println("EOF reached")
			break
		} else if err != nil {
			fmt.Printf("Serial port error: %+v\n", err)
			return
		}
		fmt.Printf("%+v\n", m)
	}

}

初始化

type MPort struct {
	Port *serial.Port
}

func (s MPort) Write(buf []byte) (n int, err error) {
	if s.Port == nil {
		s.Port = newConn()//单例
	}
	return s.Port.Write(buf)
}

可以在一个enter.go里统一完成全局变量初始化,而不需要注入

posted @ 2024-04-29 17:06  蓝天上的云℡  阅读(15)  评论(0编辑  收藏  举报