Go language network communication --- string and int conversion, int64 and [] byte conversion, int direct conversion, string and [] byte conversion

Convert between string and int

#string到int  
int,err:=strconv.Atoi(string)  
#string到int64  
int64, err := strconv.ParseInt(string, 10, 64)  
#int到string  
string:=strconv.Itoa(int)  
#int64到string  
string:=strconv.FormatInt(int64,10)

int64 and [] byte interchange

package main

import (
    "fmt"
    "encoding/binary"
)

func main() {
    var i int64 = 2323
    buf := Int64ToBytes(i)
    fmt.Println(buf)
    fmt.Println(BytesToInt64(buf))
}

func Int64ToBytes(i int64) []byte {
    var buf = make([]byte, 8)
    binary.BigEndian.PutUint64(buf, uint64(i))
    return buf
}

func BytesToInt64(buf []byte) int64 {
    return int64(binary.BigEndian.Uint64(buf))
}

transfer between int


    #Efficient writing 
package main 

import ( 
    "unsafe" 
) 

func main () { 
    // set an int64 data int64_num: = int64 (6) 
    // convert int64 to int 
    int_num: = * (* int) (unsafe.Pointer ( & int64_num)) 
    println (int_num) 
}

Direct conversion is also possible

E.g:

int(int64)

int64(int)

string and [] byte interchange

[]byte 转 string:

      string([]byte)

string 转 []byte:

     []byte(string)

Guess you like

Origin www.cnblogs.com/yunweiqiang/p/12735362.html