LoginSignup
1
0

More than 1 year has passed since last update.

16進数、バイナリ、base64の相互変換をCLIとGo(Golang)でやる

Posted at

要はこれをやるのだ(相互変換)

hexadecimal
 ↓       ↑
  binary
 ↓       ↑
  base64

CLIでやる

まず 16進数 to base64

echo "0123456789abcdef" | xxd -r -p | base64 # ASNFZ4mrze8=

base64 to 16進数

echo "ASNFZ4mrze8=" | base64 -d | hexdump # 0000000 01 23 45 67 89 ab cd ef

Golangでやる

package main

import (
    "encoding/base64"
    "encoding/hex"
    "fmt"
)

func main() {
    hexStr := "0123456789abcdef"

    // hexadecimal string -> byte -> base64 string
    b64Str, _ := hexToBase64(hexStr) // ASNFZ4mrze8=
    fmt.Printf("hex string -> byte -> base64 string: %s\n", b64Str)

    // base64 string -> byte -> hexadecimal string
    hexStr, _ = base64ToHex(b64Str) // 0123456789abcdef
    fmt.Printf("base64 string -> byte -> hex string: %s\n", hexStr)
}

func hexToBase64(in string) (out string, err error) {
    hexStr, err := hex.DecodeString(in)
    out = base64.StdEncoding.EncodeToString(hexStr)
    return
}

func base64ToHex(in string) (out string, err error) {
    b64Str, err := base64.StdEncoding.DecodeString(in)
    out = hex.EncodeToString(b64Str)
    return
}

結果

hex string -> byte -> base64 string: ASNFZ4mrze8=
base64 string -> byte -> hex string: 0123456789abcdef
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0