SoFunction
Updated on 2025-03-04

Operation of converting golang value type to []uint8 type

In go language, byte is actually an alias for uint8, and byte and uint8 can be directly transferred.

At present, ints in the range 0~255 can only be converted into byte.

func Int64ToBytes(num int64) []uint8 {
 var buffer 
 err := (&buffer, , num)
 if err != nil {
  ("int64 to[]uint8 failed %v", err)
 }
 return ()
}

When using(), you should pay attention to some issues:

Write writes the binary representation of data into w.

Data must be a fixed-size value or a slice of fixed-size // values, or a pointer to such data.

Boolean values encode as one byte: 1 for true, and 0 for false.

Bytes written to w are encoded using the specified byte order and read from successive fields of the data. When writing structs, zero values are written for fields with blank (_) field names.

My translation is like this (I don’t have good English, don’t blame me!)

Write writes the binary representation of the data to w.

The data must be a fixed-size value or a slice of a fixed-size value, or a pointer to such data

The Boolean value is encoded as one byte: 1 means true and 0 means false.

The bytes written to w are encoded in the specified byte order and read from consecutive fields of the data.

When writing to a structure, a zero value name is written to the blank (_) field.

Supplement: Golang's json conversion problem with json library is a relatively easy trap for json library.

Similar to this CA, if the instance is converted into a string.

type CA struct {
 List []uint8
}
 
func main() {
 ca := CA{[]uint8{1,2,3,4,5,6,7,8,9,0}}
 r, _ := (ca)
 (string(r)) //{"List":"AQIDBAUGBwgJAA=="}
}

What we want is to have a normal json. Only an 8-bit json library such as int8 byte uint8 will be processed as a string for us. If you want to solve it, you can't use these types if you want to use them. You need to use 16 32 64-bit numbers to convert them into a json string normally.

{"List":[1,2,3,4,5,6,7,8,9,0]}

But don't worry. Unmarshal, a json string we think is unwanted, will get the desired result.

If it is cross-language json communication, be careful.

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.