DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on

2 1

ประกอบ slice ของ byte ด้วย bytes.Buffer

#go

ช่วงนี้ทำงานกับ binary data บ่อยๆเพื่อทำการ encode/decode ข้อมูลที่อยู่ในรูปแบบ binary สิ่งที่เราต้องทำประจำคือเอาข้อมูลแบบ binary ที่อยู่ใน slice ของ byte ([]byte) มารวมๆกันให้เป็น byte slice ก้อนใหญ่ก้อนนึง

ท่าในการเอา byte slice สองอันมารวมกันท่านึงที่นึกออกคือใช้ฟังก์ชัน append เช่นมีข้อมูลแบบนี้

a := []byte("Hello")
b := []byte("World")
Enter fullscreen mode Exit fullscreen mode

เอา a และ b มารวมกันด้วย append ได้แบบนี้

s := append(a, b...)
Enter fullscreen mode Exit fullscreen mode

แต่ว่านอกจากการใช้ append แล้วเรายังใช้ type bytes.Buffer ช่วยได้

bytes.Buffer (https://pkg.go.dev/bytes#Buffer) นั้นซ่อนข้อมูล []byte เอาไว้แล้วเตรียม method ที่ implements interface Reader และ Writer เอาไว้ให้ ทำให้เราประกอบข้อมูล []byte ผ่านทาง method พวกนี้ได้ และใช้ method/function อื่นๆที่ทำงานกับ Reader และ Writer ได้อีกด้วย

ตัวอย่างเราสามารถประกอบ a และ b ได้โดยการใช้ bytes.Buffer ได้ดังนี้

var buf bytes.Buffer

buf.Write(a)
buf.Write(b)
s := buf.Bytes()
Enter fullscreen mode Exit fullscreen mode

ตัวอย่างที่ซับซ้อนขึ้นเช่นถ้าเราต้องการแปลงตัวเลข 32 bits (4 bytes) เป็น binary format เช่นมีเลข 65535 แปลงเป็น 32 bits format จะได้ 00000000000000001111111111111111 เขียนอยู่ในรูป byte slice จะได้ []byte{0, 0, 255, 255}

เราจะใช้ package binary ช่วยแปลงเลขเป็น byte slice แล้ว Write เข้าไปใน buffer แบบนี้

i := uint32(65535)
c := make([]byte, 4)
binary.BigEndian.PutUint32(c, i)
buf.Write(c)
Enter fullscreen mode Exit fullscreen mode

แต่เนื่องจากว่า bytes.Buffer นั้น implements Writer เอาไว้เราเลยเขียนแบบนี้ได้สั้นกว่า

i := uint32(65535)
binary.Write(&buf, binary.BigEndian, i)
Enter fullscreen mode Exit fullscreen mode

เพราะ binary.Write ค่าแรกนั้นรับ Writer นั่นเอง

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay