Golang converts the int of byte

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

When using Golang for data transmission, you will often encounter the mutual transfer of byte and int, but Golang does not have a ready-made method, so it can only be solved by binary package.

So, need: Import "encoding/binary", and because it is a byte conversion, so also involves Bytes:import "bytes"

The code is as follows:

Package Main

Import (

"Bytes"

"Encoding/binary"

"FMT"

"Strings"

)

Func Main () {

b : = []byte{0x00, 0x00, 0x03, 0xe8}

B_buf : = bytes . Newbuffer (b)

var x int32

Binary. Read (b_buf, Binary. Bigendian, &x)

Fmt. PRINTLN (x)

Fmt. PRINTLN (Strings. Repeat ("-", 100))

x =

b_buf = bytes . Newbuffer ([]byte{})

Binary. Write (b_buf, Binary. Bigendian, X)

Fmt. Println (b_buf. Bytes ())

}

This is basically the solution. In fact, the following does not assign value x also does not matter. Because it's already.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.