golang byte 操作

來源:互聯網
上載者:User

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)
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.