SoFunction
Updated on 2025-03-05

golang implements conversion operations between integer and byte array

I won't say much nonsense, let's just read the code~

//isSymbol means whether there is a signfunc BytesToInt(b []byte, isSymbol bool) (int, error){
 if isSymbol {
 return bytesToIntS(b)
 }
 return bytesToIntU(b)
}

//The number of bytes (big endian) group is converted into int (unsigned)func bytesToIntU(b []byte) (int, error) {
 if len(b) == 3 {
 b = append([]byte{0},b...)
 }
 bytesBuffer := (b)
 switch len(b) {
 case 1:
 var tmp uint8
 err := (bytesBuffer, , &tmp)
 return int(tmp), err
 case 2:
 var tmp uint16
 err := (bytesBuffer, , &tmp)
 return int(tmp), err
 case 4:
 var tmp uint32
 err := (bytesBuffer, , &tmp)
 return int(tmp), err
 default:
 return 0,("%s", "BytesToInt bytes lenth is invaild!")
 }
}

//The number of bytes (big endian) group is converted into int (signed)func bytesToIntS(b []byte) (int, error) {
 if len(b) == 3 {
 b = append([]byte{0},b...)
 }
 bytesBuffer := (b)
 switch len(b) {
 case 1:
 var tmp int8
 err := (bytesBuffer, , &tmp)
 return int(tmp), err
 case 2:
 var tmp int16
 err := (bytesBuffer, , &tmp)
 return int(tmp), err
 case 4:
 var tmp int32
 err := (bytesBuffer, , &tmp)
 return int(tmp), err
 default:
 return 0,("%s", "BytesToInt bytes lenth is invaild!")
 }
}

//Convert the shaping into bytesfunc IntToBytes(n int,b byte) ([]byte,error) {
 switch b {
 case 1:
 tmp := int8(n)
 bytesBuffer := ([]byte{})
 (bytesBuffer, , &tmp)
 return (),nil
 case 2:
 tmp := int16(n)
 bytesBuffer := ([]byte{})
 (bytesBuffer, , &tmp)
 return (),nil
 case 3,4:
 tmp := int32(n)
 bytesBuffer := ([]byte{})
 (bytesBuffer, , &tmp)
 return (),nil
 }
 return nil,("IntToBytes b param is invaild")
}

Supplement: golang integer, float and byte conversion

Use scenarios:

In TCP protocol transmission, in order to prevent sticking packets, you need to send message headers first, that is, send data length first, write the real data according to the length, but since network transmissions are all byte streams, how can you convert the integer into byte streams?

Just four steps:

Convert ----int to int64

Apply ----Apply for a byte buffer

Write---Write data to the buffer in binary

Take out ----Fetch out of buffer in byte stream

func IntToBytes(n int)[]byte{
 data:=int64(n)//Data type conversion bytebuffer:=([]byte{})//Byte collection (bytebuffer,,data)//Write bytes according to binary return ()//Return byte combination}

Decoding also requires two steps:

1. Create a buffer() with byte stream as its content

2. Read binary encoded data from buf buffer and assign it to data

func BytesToInt(bs []byte)int{
 bytebuffer:=(bs) //Write binary combination according to binary var data int64
 (bytebuffer,,&data) //decoding return int(data)
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.