在 Golang 中将 int 数组转换为字节数组

我正在尝试创建一些随机 int 数组并将其写入xyz.txtGolang 中的文件。

如何将ids哪个是int数组转换为byte数组,作为参数file.Write接受[]byte。将随机整数数组写入文本文件的正确方法是什么。


func main() {

    var id int

    var ids []int

    var count int


    f, err := os.Create("xyz.txt")

    check(err)


    defer f.Close()


    for j := 0; j < 5; j++ {

        count = rand.Intn(100)

        for i := 0; i < product_count; i++ {

            id = rand.Intn(1000)

            ids = append(product_ids, product_id)

        }

        n2, err := f.Write(ids)

        check(err)

        fmt.Printf("wrote %d bytes\n", n2)

    }

}


至尊宝的传说
浏览 459回答 1
1回答

回首忆惘然

您可以使用fmt.Fprint, 作为这个简化的工作示例:package mainimport (&nbsp; &nbsp; "bufio"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math/rand"&nbsp; &nbsp; "os")func main() {&nbsp; &nbsp; f, err := os.Create("xyz.txt")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; defer f.Close()&nbsp; &nbsp; w := bufio.NewWriter(f)&nbsp; &nbsp; defer w.Flush()&nbsp; &nbsp; for j := 0; j < 5; j++ {&nbsp; &nbsp; &nbsp; &nbsp; count := 4 //count := rand.Intn(100)&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < count; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprint(w, rand.Intn(1000), " ")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintln(w)&nbsp; &nbsp; }}xyz.txt输出文件:81 887 847 59&nbsp;81 318 425 540&nbsp;456 300 694 511&nbsp;162 89 728 274&nbsp;211 445 237 106&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python