search
HomeBackend DevelopmentGolangHow to marshal integer values ​​to hex using go-yaml?

如何使用 go-yaml 将整数值编组为十六进制?

php editor Banana will introduce you how to use go-yaml to marshal integer values ​​into hexadecimal. go-yaml is a Go language library for processing YAML format data, which provides a simple and easy-to-use API. To marshal an integer value into hexadecimal, we can first convert the integer to a byte slice and then use the fmt.Sprintf function to format the byte slice into a hexadecimal string. Finally, we can use the go-yaml library to write the formatted string into a YAML file. This method is simple and efficient and can meet our needs. Next, let us take a closer look at the specific implementation steps.

Question content

I have a struct with an integer field that is meaningful to humans in a hexadecimal representation. For example, set it to the Vendor ID field.

I want to save this data to a YAML file for manual editing and then load it from the file. As far as I understand there is no problem with hexadecimal representation of numbers in YAML itself, but go-yaml (I use v3) encodes integers in decimal form and I haven't found a way Normal way to have it save them in hexadecimal form.

Let’s take the following code as a starting point:

import (
    //...
    "gopkg.in/yaml.v3"
)

type DeviceInfo struct {
    VendorId uint32 `yaml:"vendorid"`
}

func main() {
    deviceInfo := DeviceInfo{VendorId: 0xdeadbeef}

    yml, err := yaml.Marshal(deviceInfo)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(yml))
}

This code generates YAML with decimal values:

vendorid: 3735928559

Next, go-yaml allows you to create custom marshalers for your own types. I did this (I intentionally omitted the 0x prefix in the fmt.Sprintf() format string):

type Uint32Hex uint32

func (U Uint32Hex) MarshalYAML() (interface{}, error) {
    return fmt.Sprintf("%x", U), nil
}

type DeviceInfo struct {
    VendorId Uint32Hex `yaml:"vendorid"`
}

func main() {
    // the same code
}

This code generates hexadecimal values ​​without the 0x prefix (which is logical for now):

vendorid: deadbeef

But if I add 0x prefix in custom marshaler:

func (U Uint32Hex) MarshalYAML() (interface{}, error) {
    return fmt.Sprintf("0x%x", U), nil
}

The value is generated correctly, but instead of a number, it is a string:

vendorid: "0xdeadbeef"

In order to unmarshal this row into numbers, I also had to write a custom unmarshaler. I don't like this solution.

Finally I have the following questions:

  1. Is there an easy way to generate hexadecimal numbers using go-yaml that I haven't found?

  2. Is it possible to make a custom encoder based on go-yaml as an extension of the package, without changing the package itself? For me, a more convenient way is to pass the format tag in the structure description, for example, like this:

    type DeviceInfo struct {
        VendorId uint32 `yaml:"vendorid,hex"`
    }
    
  3. If this requires changes to the package code, what is Go's approach to this situation? Just copy the package file into my project, modify it as needed and import locally?

Workaround

The problem here is that quoting the string in yaml is optional, but go-yaml uses the same as the JSON encoder Internal architecture. This means that custom marshaling is handled first and then the citation logic is applied completely independently. deadbeef is not quoted, but 0xdeadbeef is quoted because the latter is a number . It's quoted so that it doesn't accidentally unmarshal into a number because your custom marshaler returns a string when it knows it's supposed to be a string. Since deadbeef cannot be read as a valid number, no quotes are needed. You can do two things:

  1. Complete custom marshalling/unmarshaling from strings:
func (U *Uint32Hex) UnmarshalYAML(value *yaml.Node) error {
    parsed, err := strconv.ParseUint(value.Value, 0, 32)
    *U = Uint32Hex(parsed)
    return err
}
  1. Fork go-yaml and modify it. If you do this, the imports in the source file should not be changed. Instead, you should add the replace directive to go.mod like this:
require gopkg.in/yaml.v3 v3.0.1

replace gopkg.in/yaml.v3 v3.0.1 => ../yaml.v3 // Your local path to the fork

I prefer solution 1 because it allows you to serialize the values ​​any way you like without deviating from the yaml generated by others, and doesn't require you to maintain a branch.

The above is the detailed content of How to marshal integer values ​​to hex using go-yaml?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool