Help us understand the problem. What is going on with this article?

バイナリデータを Golang の []byte リテラル表記に変換する簡単なお仕事

More than 1 year has passed since last update.

こんなの絶対誰かが作ってるし探せば転がってるんだろうけどググるのも面倒くさくなったので自分で作りました。

以下は README に書いた内容。まぁ実質のコードはたったこれだけで

package godump

import (
    "bytes"
    "fmt"
    "io"
)

//DumpBytes returns []bytes literal string
func DumpBytes(r io.Reader, name string) (io.Reader, error) {
    buf := new(bytes.Buffer)
    b := make([]byte, 1)
    var err error
    sep := fmt.Sprintf("var %s = []byte{", name)
    for true {
        if _, err = r.Read(b); err != nil {
            break
        }
        fmt.Fprintf(buf, "%s%#02x", sep, b)
        sep = ", "
    }
    fmt.Fprintln(buf, "}")
    return buf, nil
}

外部パッケージとして読み込む価値もないので,もし使いたいという奇特な方がおられるなら,中身見て適当にコピペしてください。

Install

$ go get github.com/spiegel-im-spiegel/godump

Installing by dep.

$ dep ensure -add github.com/spiegel-im-spiegel/godump

Usage

dump, err := godump.DumpBytes(bytes.NewBufferString("hello world"), "foobar")
if err != nil {
    return
}
io.Copy(os.Stdout, dump)
// Output:
// var foobar = []byte{0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64}

Command Line Interface

$ godump -h
Usage:
  godump [flags] [binary file]

Flags:
  -h, --help          help for godump
  -n, --name string   value name (default "dumpList")
$ echo hello world | godump -n foobar
var foobar = []byte{0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0a}
$ cat input.txt
hello world

$ godump -n foobar input.txt
var foobar = []byte{0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64}
spiegel-im-spiegel
職業エンジニアは無期休業中。
https://baldanders.info/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした