Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Marshaling integer values to hexadecimal representation #1010

Open
xtheandrew opened this issue Dec 15, 2023 · 1 comment
Open

Marshaling integer values to hexadecimal representation #1010

xtheandrew opened this issue Dec 15, 2023 · 1 comment

Comments

@xtheandrew
Copy link

How can I marshal a number from a structure to YAML in hexadecimal representation?

I have a structure with integer fields, the representation of which makes sense to humans in hexadecimal form. I want to save this data to a YAML file for manual editing and then load it from the file. go-yaml (I use v3) encodes integers in decimal form only.

I tried to make a custom marshaler based on the documentation (playground link):

type Uint32Hex uint32

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

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

But in this case, the number is generated as a string:

vendorid: "0xdeadbeef"

And in order to then unmarshal this line into a number, I will also have to write a custom unmarshaler.

Is there any other way?

So far, I've made a fork and added the ability to set the format in the form of structure tags:

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

I replaced the module in go.mod and that solved my problem for now. But it would be nice to have a built-in feature.

@AXDOOMER
Copy link

I would love for this fix to be available in the standard library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants