LoginSignup
13
8

More than 5 years have passed since last update.

[]byte型をuint・int・stringに相互変換するヘルパー関数

Last updated at Posted at 2017-03-20

はじめに

  • いつもの通り、備忘録的めもです
  • ビット・バイトのエンディアンに注意
  • 気になるとことかあればコメントにて

コード

package helpers

import (
    "encoding/binary"
    "fmt"
    "strconv"
    "strings"
)

// Str2bytes converts string("00 00 00 00 00 00 00 00") to []byte
func Str2bytes(str string) []byte {
    bytes := make([]byte, 8)
    for i, e := range strings.Fields(str) {
        b, _ := strconv.ParseUint(e, 16, 64)
        bytes[i] = byte(b)
    }
    return bytes
}

// Bytes2str converts []byte to string("00 00 00 00 00 00 00 00")
func Bytes2str(bytes ...byte) string {
    strs := []string{}
    for _, b := range bytes {
        strs = append(strs, fmt.Sprintf("%02x", b))
    }
    return strings.Join(strs, " ")
}

// Bytes2uint converts []byte to uint64
func Bytes2uint(bytes ...byte) uint64 {
    padding := make([]byte, 8-len(bytes))
    i := binary.BigEndian.Uint64(append(padding, bytes...))
    return i
}

// Uint2bytes converts uint64 to []byte
func Uint2bytes(i uint64, size int) []byte {
    bytes := make([]byte, 8)
    binary.BigEndian.PutUint64(bytes, i)
    return bytes[8-size : 8]
}

// Bytes2int converts []byte to int64
func Bytes2int(bytes ...byte) int64 {
    if 0x7f < bytes[0] {
        mask := uint64(1<<uint(len(bytes)*8-1) - 1)

        bytes[0] &= 0x7f
        i := Bytes2uint(bytes...)
        i = (^i + 1) & mask
        return int64(-i)

    } else {
        i := Bytes2uint(bytes...)
        return int64(i)
    }
}

// Int2bytes converts int to []byte
func Int2bytes(i int, size int) []byte {
    var ui uint64
    if 0 < i {
        ui = uint64(i)
    } else {
        ui = (^uint64(-i) + 1)
    }
    return Uint2bytes(ui, size)
}
13
8
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
13
8