21天精品區塊鏈課程免費學習,深入實戰行家帶路,助力開發人員輕鬆玩轉區塊鏈!>>>
byte數組轉int
// bytes to int 32func bytesTo32Int(b []byte) int {buf := bytes.NewBuffer(b)var tmp uint32binary.Read(buf, binary.BigEndian, &tmp)return int(tmp)}// bytes to int 16func bytesTo16Int(b []byte) int {buf := bytes.NewBuffer(b)var tmp uint16binary.Read(buf, binary.BigEndian, &tmp)return int(tmp)}
int轉byte數組
// int to 4 bytesfunc intTo4Bytes(i int) []byte {buf := bytes.NewBuffer([]byte{})tmp := uint32(i)binary.Write(buf, binary.BigEndian, tmp)return buf.Bytes()}// int to 2 bytesfunc intTo2Bytes(i int) []byte {buf := bytes.NewBuffer([]byte{})tmp := uint16(i)binary.Write(buf, binary.BigEndian, tmp)return buf.Bytes()}
byte數組轉16進位字串
// bytes to hex stringfunc bytesToHexString(b []byte) string {var buf bytes.Bufferfor _, v := range b {t := strconv.FormatInt(int64(v), 16)if len(t) > 1 {buf.WriteString(t)} else {buf.WriteString("0" + t)}}return buf.String()}
16進位字串轉byte數組
// hex string to bytesfunc hexStringToBytes(s string) []byte {bs := make([]byte, 0)for i := 0; i < len(s); i = i + 2 {b, _ := strconv.ParseInt(s[i:i+2], 16, 16)bs = append(bs, byte(b))}return bs}
二進位字串轉byte
a, err := strconv.ParseInt("11111111", 2, 16)