>> 1 package main
2
3 import "fmt"
4
5
6 func main() {
7 | var testData string = "hello"
8 |
9 | //字符串转切片
10 | slice := []byte(testData)
11 | fmt.Printf("slice:%v\n", slice)
12
13 | //切片转字符串
14 | strData := string(slice)
15 | fmt.Printf("slice:%s\n", strData)
10 }
结果:
slice:[104 101 108 108 111]
slice:hello
>> 1 package main
2
3 import (
4 | "encoding/binary"
5 | "fmt"
6 )
7
8
9 func main() {
10 | var intData uint32 = 1024
11 | var sliceData []byte
12
13 | //整型转切片
14 | sliceData = make([]byte, 4)
15 | binary.LittleEndian.PutUint32(sliceData, intData)
16 | fmt.Printf("intData:%v\n", sliceData)
17
18 | //切片转整型
19 | aa := binary.LittleEndian.Uint32(sliceData)
20 | fmt.Printf("aa:%v\n", aa)
21 }
结果:
intData:[0 4 0 0]
aa:1024
整形转换成字节
func IntToBytes(n int) []byte {
x := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()
}
字节转换成整形
func BytesToInt(b []byte) int {
bytesBuffer := bytes.NewBuffer(b)
var x int32
binary.Read(bytesBuffer, binary.BigEndian, &x)
return int(x)
}
**上边存在问题-补充:**
```cpp
//isSymbol表示有无符号
func BytesToInt(b []byte, isSymbol bool) (int, error){
if isSymbol {
return bytesToIntS(b)
}
return bytesToIntU(b)
}
//字节数(大端)组转成int(无符号的)
func bytesToIntU(b []byte) (int, error) {
if len(b) == 3 {
b = append([]byte{0},b...)
}
bytesBuffer := bytes.NewBuffer(b)
switch len(b) {
case 1:
var tmp uint8
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 2:
var tmp uint16
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 4:
var tmp uint32
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
default:
return 0,fmt.Errorf("%s", "BytesToInt bytes lenth is invaild!")
}
}
//字节数(大端)组转成int(有符号)
func bytesToIntS(b []byte) (int, error) {
if len(b) == 3 {
b = append([]byte{0},b...)
}
bytesBuffer := bytes.NewBuffer(b)
switch len(b) {
case 1:
var tmp int8
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 2:
var tmp int16
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
case 4:
var tmp int32
err := binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp), err
default:
return 0,fmt.Errorf("%s", "BytesToInt bytes lenth is invaild!")
}
}
//整形转换成字节
func IntToBytes(n int,b byte) ([]byte,error) {
switch b {
case 1:
tmp := int8(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, &tmp)
return bytesBuffer.Bytes(),nil
case 2:
tmp := int16(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, &tmp)
return bytesBuffer.Bytes(),nil
case 3,4:
tmp := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, &tmp)
return bytesBuffer.Bytes(),nil
}
return nil,fmt.Errorf("IntToBytes b param is invaild")
}
四、结构体和切片之间的转换
>> 1 package main
2
3 import (
4 | "bytes"
5 | "encoding/binary"
6 | "fmt"
7 )
8
9
10 func main() {
11 | type structData struct {
12 | | intData uint32
13 | | strData []byte
14 | }
15
16 | var ss = structData{intData: 12}
17 | var buffer = bytes.Buffer{}
18 | err := binary.Write(&buffer, binary.BigEndian, ss.intData)
19 | if err != nil {
20 | | fmt.Printf("err")
21 | }
22
23 | ss.strData = make([]byte, 10)
24 | copy(ss.strData, []byte("heloo"))
25 | err = binary.Write(&buffer, binary.BigEndian, ss.strData)
26 | if err != nil {
27 | | fmt.Printf("err")
28 | }
29
30 | fmt.Printf("struct:%v\n", buffer)
31 }
结果:
struct:{[0 0 0 12 104 101 108 111 111 0 0 0 0 0] 0 0}
由于err = binary.Write(&buffer, binary.BigEndian, ss.strData)
这个函数的最后一个参数是需要有固定大小的参数,才能写入,因此 如果没有初始化的话,会之间报错。
如果结构体中的各个 参数 都是有固定长度的也可以这样写:
>> 1 package main
2
3 import (
4 | "bytes"
5 | "encoding/binary"
6 | "fmt"
7 )
8
9
10 func main() {
11 | type structData struct {
12 | | intData uint32
13 | | strData uint32
14 | }
15
16 | var ss = structData{intData: 12, strData: 12}
17 | var buffer = bytes.Buffer{}
18 | err := binary.Write(&buffer, binary.BigEndian, ss.intData)
19 | if err != nil {
20 | | fmt.Printf("err")
21 | }
22
23 | err = binary.Write(&buffer, binary.BigEndian, ss.strData)
24 | if err != nil {
25 | | fmt.Printf("err")
26 | }
27
28 | fmt.Printf("struct:%v\n", buffer)
29 }
~
结果:
struct:{[0 0 0 12 0 0 0 12] 0 0}
>> 1 package main
2
3 import (
4 | "fmt"
5 | "strconv"
6 )
7
8
9 func main() {
10 | //字符串转整型
11 | ss, err := strconv.Atoi("12")
12 | if err != nil {
13 | | fmt.Printf("err")
14 | }
15 | fmt.Printf("ss:%d\n", ss)
16
17 | aa := strconv.Itoa(ss)
18 | fmt.Printf("aa:%s\n", aa)
19
20 }
结果:
ss:12
aa:12
补充:
v1 := "100"
v2, _ := strconv.Atoi(v1) // 将字符串转化为整型,v2 = 100
v3 := 100
v4 := strconv.Itoa(v3) // 将整型转化为字符串, v4 = "100"
v5 := "true"
v6, _ := strconv.ParseBool(v5) // 将字符串转化为布尔型
v5 = strconv.FormatBool(v6) // 将布尔值转化为字符串
v7 := "100"
v8, _ := strconv.ParseInt(v7, 10, 64) // 将字符串转化为整型,第二个参数表示进制,第三个参数表示最大位数
v7 = strconv.FormatInt(v8, 10) // 将整型转化为字符串,第二个参数表示进制
v9, _ := strconv.ParseUint(v7, 10, 64) // 将字符串转化为无符号整型,参数含义同 ParseInt
v7 = strconv.FormatUint(v9, 10) // 将字符串转化为无符号整型,参数含义同 FormatInt
v10 := "99.99"
v11, _ := strconv.ParseFloat(v10, 64) // 将字符串转化为浮点型,第二个参数表示精度
v10 = strconv.FormatFloat(v11, 'E', -1, 64)
q := strconv.Quote("Hello, 世界") // 为字符串加引号
q = strconv.QuoteToASCII("Hello, 世界") // 将字符串转化为 ASCII 编码
1 package main
2
3 import "fmt"
4
5 func main() {
6 | var testData string = "hello"
7 | var testData1 [20]byte
8 | var testData2 [20]byte
9
10 | //字符串转切片
11 | slice := []byte(testData)
12 | fmt.Printf("slice:%v\n", slice)
13
14 | //切片转数组
15 | copy(testData1[:], slice)
16 | fmt.Printf("数组1:%s\n", testData1)
17
18 | //数组的复制
19 | copy(testData2[:], testData1[:])
20 | fmt.Printf("数组2:%s\n", testData1)
21 }
1、[]byte 转 io.Reader
package main
import (
"bytes"
"fmt"
"log"
)
func main() {
data := []byte("Hello AlwaysBeta")
// byte slice to bytes.Reader, which implements the io.Reader interface
reader := bytes.NewReader(data)
// read the data from reader
buf := make([]byte, len(data))
if _, err := reader.Read(buf); err != nil {
log.Fatal(err)
}
fmt.Println(string(buf))
}
2、io.Reader 转 []byte
package main
import (
"bytes"
"fmt"
"strings"
)
func main() {
ioReaderData := strings.NewReader("Hello AlwaysBeta")
// creates a bytes.Buffer and read from io.Reader
buf := &bytes.Buffer{}
buf.ReadFrom(ioReaderData)
// retrieve a byte slice from bytes.Buffer
data := buf.Bytes()
// only read the left bytes from 6
fmt.Println(string(data[6:]))
}
var f float64
bits = *(*uint64)(unsafe.Pointer(&f))
type ptr unsafe.Pointer
bits = *(*uint64)(ptr(&f))
var p ptr = nil
float64就强制转换成uint64类型,float的地址就是一个值但是类型是float64,然后创建了一个uint64类型变量,地址值也是float64的地址值,两个变量值相同类型不同,强制转换了类型。
unsafe强制转换是指针的底层操作了,用c的朋友就很熟悉这样的指针类型转换,利用内存对齐才能保证转换可靠,例如int和uint存在符号位差别,利用unsafe转换后值可能不同,但是在内存存储二进制一模一样。