1.数值字母、字符串转整型值
strconv.Atoi("3")
2.整型值转字符
strconv.Itoa(3)
3.字符串转字节码
bytes := []byte("12345678")
4.字节码转字符串
str := fmt.Sprintf("%x", bytes)
str := string(bytes)
import "encoding/hex"
str := hex.EncodeToString(bytes)
5.int64与字节码
func Int64ToBytes(value int64) []byte {
var bytes = make([]byte, 8)
binary.BigEndian.PutUint64(bytes, uint64(value))
return bytes
}
func BytesToInt64(bytes []byte) uint64 {
return int64(binary.BigEndian.Uint64(bytes))
}
func BytesNtohll(b []byte) uint64 {
return uint64(b[0])<<56 | uint64(b[1])<<48 |
uint64(b[2])<<40 | uint64(b[3])<<32 |
uint64(b[4])<<24 | uint64(b[5])<<16 |
uint64(b[6])<<8 | uint64(b[7])
}
6.int与字节码
func InttoBytes(value uint32) []byte {
bytes := make([]byte, 4)
bytes[0] = uint8(value >> 24)
bytes[1] = uint8(value >> 16)
bytes[2] = uint8(value >> 8)
bytes[3] = uint8(value)
return []byte(bytes)
}
func BytesNtohl(b []byte) uint32 {
return uint32(b[0])<<24 | uint32(b[1])<<16 |
uint32(b[2])<<8 | uint32(b[3])
}
func BytesHtohl(b []byte) uint32 {
return uint32(b[3])<<24 | uint32(b[2])<<16 |
uint32(b[1])<<8 | uint32(b[0])
}
7.字符串IP转整形(字节码)
func InetAton(ip string) uint32 {
buffer := strings.Split(ip, ".")
first, _ := strconv.Atoi(buffer[0])
second, _ := strconv.Atoi(buffer[1])
third, _ := strconv.Atoi(buffer[2])
fourth, _ := strconv.Atoi(buffer[3])
var int_ip uint32
int_ip += uint32(first << 24)
int_ip += uint32(second << 16)
int_ip += uint32(third << 8)
int_ip += uint32(fourth)
return int_ip
}
func IPv4Ntoa(ip uint32) string {
return fmt.Sprintf("%d.%d.%d.%d",
byte(ip>>24), byte(ip>>16),
byte(ip>>8), byte(ip))
}
8.int32转string
// string 转 int32
num, err := strconv.ParseInt(`123456`, 10, 32)
if err != nil {
panic(err)
}
// int32 转 string
str := strconv.FormatInt(123456, 10)
println(str)