This content originally appeared on DEV Community and was authored by Weerasak Chongnguluam
ช่วงนี้ต้องจัดการข้อมูลที่เป็น binary ซึ่งบางครั้งข้อมูลอยู่ในรูปแบบ BCD ซึ่งถ้าให้เขียนเป็นเลขฐานสองโดยตรงก็จะยาว และยากต่อการอ่านเวลา debug เกินไป ดังนั้นก็เลยแปลงให้อยู่ในเลขฐานสิบหกดีกว่าเวลาต้อง debug หรือ log ข้อมูล
สำหรับ Go มี package encoding/hex
ที่มีฟังก์ชันให้เราใช้แปลงไปมาระหว่าง binary data ([]byte
) ไปเป็น hexadecimal string
ได้ง่ายๆอยู่ คือฟังก์ชัน
func EncodeToString(src []byte) string
func DecodeString(s string) ([]byte, error)
ตัวอย่างการใช้งานเช่น เมื่อเราต้องการแปลงจาก Hex ที่เป็น string กลับไปเป็น binary data
package main
import (
"encoding/hex"
"fmt"
"log"
)
func main() {
bcdNumberHex := "1234"
bcdNumberBytes, err := hex.DecodeString(bcdNumberHex)
if err != nil {
log.Fatal(err)
}
for _, b := range bcdNumberBytes {
fmt.Printf("0x%x ", b)
}
// Output:
// 0x12 0x34
}
ตัวอย่างการใช้งานเช่น เมื่อเราต้องการแปลงจาก binary data กลับไปเป็น Hex string
package main
import (
"encoding/hex"
"fmt"
)
func main() {
bcdNumberBytes := []byte{0x12, 0x34}
bcdNumberHex := hex.EncodeToString(bcdNumberBytes)
fmt.Println(bcdNumberHex)
// Output:
// 1234
}
This content originally appeared on DEV Community and was authored by Weerasak Chongnguluam

Weerasak Chongnguluam | Sciencx (2021-09-04T04:50:34+00:00) Encode / Decode Hexadecimal string to/from binary data. Retrieved from https://www.scien.cx/2021/09/04/encode-decode-hexadecimal-string-to-from-binary-data/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.