Home  >  Article  >  Backend Development  >  How to read binary data using Golang

How to read binary data using Golang

WBOY
WBOYOriginal
2024-03-20 21:12:041091browse

How to read binary data using Golang

How to read binary data using Golang

In Golang, we can use os and encoding/binary package to read binary data. Next, we will introduce in detail how to implement the method of reading binary data through these two packages, and attach specific code examples.

Use the os package to read binary data

First, we need to use the os.Open function to open a binary file and ensure that the file is opened successfully , and then create a byte slice to store the read binary data.

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("binary_file.bin")
    if err != nil {
        fmt.Println("File opening failed:", err)
        return
    }
    defer file.Close()

    fileInfo, _ := file.Stat()
    fileSize := fileInfo.Size()
    data := make([]byte, fileSize)

    _, err = file.Read(data)
    if err != nil {
        fmt.Println("Failed to read file:", err)
        return
    }

    fmt.Printf("Read binary data: %v
", data)
}

Parsing binary data using the encoding/binary package

Once we have read the binary data into byte slices, we can then use encoding/ binary package to parse these binary data. We need to use the binary.Read function and pass a io.Reader and a target variable to parse the binary data into the specified type.

The following example demonstrates how to read a uint16 type data from a byte slice.

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    data := []byte{0x03, 0xE8} // 1000 (binary) = 3E8 (hex) = 1000 (decimal)

    var num uint16
    err := binary.Read(bytes.NewReader(data), binary.LittleEndian, &num)
    if err != nil {
        fmt.Println("Failed to parse binary data:", err)
        return
    }

    fmt.Printf("Parsed uint16 data: %d
", num)
}

Through the above code example, we can see how to use the os and encoding/binary packages in Golang to read and parse binary data. In practical applications, we can perform corresponding processing and analysis according to specific needs and binary data formats.

The above is the detailed content of How to read binary data using Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn