golang - string to slice, slice to string, slice to array, array to slice, uint16 to []byte (Little Enddian), []byte to Uint32 (Little Enddian)

string => slice

출처: https://github.com/soshi8/GoLangTrans

package main

import (
  "fmt"
)

func main() {

  var aaa string
  aaa = "sample string"
  bbb := []byte(aaa)

  fmt.Printf("bbb = %s\n", bbb)
}

slice => string

package main

import (
  "fmt"
)

func main() {

  var aaa []byte
  //  aaa = []byte("sample string")
  aaa = []byte{115, 97, 109, 112, 108, 101}
  bbb := string(aaa)

  fmt.Printf("bbb = %s", bbb)
}

slice => array

package main

import (
  "fmt"
)

func main() {

  var aaa [6]byte
  var bbb []byte
  aaa = [6]byte{115, 97, 109, 112, 108, 101}
  bbb = aaa[:]

  fmt.Printf("bbb = %s", bbb[:])
}

array => slice

package main

import (
  "fmt"
)

func main() {

  var aaa []byte
  var bbb = make([]byte, 6)
  aaa = []byte{115, 97, 109, 112, 108, 101}
  copy(bbb, aaa[:])

  fmt.Printf("bbb = %s", bbb)
}

uint16 => []byte (Little Enddian)

package main

import (
  "encoding/binary"
  "fmt"
)

func main() {

  var aaa uint16 = 4011
  bbb := make([]byte, 4)

  binary.LittleEndian.PutUint16(bbb, aaa)
  fmt.Printf("LE1:%x\n", bbb)
}

[]byte => Uint32 (Little Enddian)

package main

import (
  "encoding/binary"
  "fmt"
)

func main() {

  aaa := []byte{115, 97, 109, 112}

  bbb := binary.LittleEndian.Uint32(aaa)
  fmt.Printf("LE1:%x\n", bbb)
}

이 글은 2018-06-11에 작성되었습니다.