栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

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

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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("%dn", BytesCombine1([]byte{1,2,3}, []byte{4,5,6}))
	fmt.Printf("%sn", 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.Buffer
	for 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("%dn", BytesCombine1([]byte{1, 2, 3}, []byte{4, 5, 6}))
	fmt.Printf("%sn", 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 []byte
	var res2 []byte
	one := make([]byte, 2)
	two := make([]byte, 2)
	//16进制
	one[0] = 0x00
	one[1] = 0x010
	two[0] = 0x020
	two[1] = 0x030
	res1 = 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("%sn", res3)
}
测试输出
[0 16 32 48]
[0 10 20 30]
[111 110 101 116 119 111]
onetwo
♥ 喜 欢 请 点 赞 哟 ♥
(●ˇ∀ˇ●)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/945723.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号