Go——两个[]byte数组合并成一个[]byte

编程入门 行业动态 更新时间:2024-10-11 09:29:09

Go——两个[]byte<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组合并成一个[]byte"/>

Go——两个[]byte数组合并成一个[]byte

合并 []byte 数组

  • 方式一
    • 使用 join 函数
    • 测试
  • 方式二
    • 使用 bytes.Buffer
    • 测试
  • 方式三
    • 使用 append ...
    • 测试输出

方式一

使用 join 函数

func BytesCombine1(pBytes ...[]byte) []byte {length := len(pBytes)s := make([][]byte, length)for index := 0; index < length; index++ {s[index] = pBytes[index]}sep := []byte("")return bytes.Join(s, sep)
}

或者简化为:

func BytesCombine2(pBytes ...[]byte) []byte {return bytes.Join(pBytes, []byte("-"))
}

测试

func main() {fmt.Println(BytesCombine1([]byte{1,2,3}, []byte{4,5,6}))fmt.Println(BytesCombine1([]byte("one"), []byte("two")))fmt.Printf("%d\n", BytesCombine1([]byte{1,2,3}, []byte{4,5,6}))fmt.Printf("%s\n", BytesCombine1([]byte("one"), []byte("two")))
}

输出如下:

[1 2 3 4 5 6]
[111 110 101 116 119 111]
[1 2 3 4 5 6]
onetwo

方式二

使用 bytes.Buffer

func BytesCombine3(pBytes ...[]byte) []byte {var buffer bytes.Bufferfor index := 0; index < len(pBytes); index++ {buffer.Write(pBytes[index])}return buffer.Bytes()
}

测试

func main() {fmt.Println(BytesCombine3([]byte{1, 2, 3}, []byte{4, 5, 6}))fmt.Println(BytesCombine3([]byte("one"), []byte("two")))fmt.Printf("%d\n", BytesCombine1([]byte{1, 2, 3}, []byte{4, 5, 6}))fmt.Printf("%s\n", BytesCombine3([]byte("one"), []byte("two")))
}

输出如下:

[1 2 3 4 5 6]
[111 110 101 116 119 111]
[1 2 3 4 5 6]
onetwo

方式三

使用 append …

func BytesCombine4() {var res1 []bytevar res2 []byteone := make([]byte, 2)two := make([]byte, 2)//16进制one[0] = 0x00one[1] = 0x010two[0] = 0x020two[1] = 0x030res1 = append(one[:], two[:]...)fmt.Println(res1)//10进制three := []byte{0, 10}four := []byte{20, 30}res2 = append(three, four...)fmt.Println(res2)five := []byte("one")six := []byte("two")res3 := append(five, six...)fmt.Println(res3)fmt.Printf("%s\n", res3)
}

测试输出

[0 16 32 48]
[0 10 20 30]
[111 110 101 116 119 111]
onetwo
♥ 喜 欢 请 点 赞 哟 ♥
(●ˇ∀ˇ●)

更多推荐

Go——两个[]byte数组合并成一个[]byte

本文发布于:2024-03-06 01:23:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1713983.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   两个   byte

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!