10 examples of 'golang string to byte' in Go

Every line of 'golang string to byte' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Go code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
17func StringToByte(s string) []byte {
18 return []byte(s)
19 //sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
20 //bh := reflect.SliceHeader{
21 // Data: sh.Data,
22 // Len: sh.Len,
23 // Cap: sh.Len,
24 //}
25 //return *(*[]byte)(unsafe.Pointer(&bh))
26}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

10func ByteStr(s string) []byte {
11 msgStr := strings.Trim(s, "[]\n\r")
12 msgByteStr := strings.Split(msgStr, " ")
13 msgBytes := make([]byte, len(msgByteStr))
14 for i := range msgBytes {
15 b, err := strconv.Atoi(msgByteStr[i])
16 if err != nil {
17 logex.Fatal(err)
18 }
19 msgBytes[i] = byte(b)
20 }
21 return msgBytes
22}
138func ToByte(s string) []byte {
139 sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
140 return *(*[]byte)(unsafe.Pointer(sh))
141}
309func ToByteSlice(byt [][]byte) []byte { return bytes.Join(byt, []byte{'\n'}) }
69func Itob(integer int) []byte {
70 byteArr := make([]byte, 8)
71 for i := 7; i >= 0; i-- {
72 byteArr[i] = byte(integer & 0xff)
73 integer = integer >> 8
74 }
75 return byteArr
76}
137func byteArrayToString(b []byte) string {
138 return string(b[:])
139}
536func convertValue2Bytes(t string) string {
537 switch t {
538 case "int", "int8", "int16", "int32", "int64":
539 return "[]byte(strconv.FormatInt(int64(val), 10))"
540 case "uint", "uint8", "uint16", "uint32", "uint64":
541 return "[]byte(strconv.FormatUInt(val, 10))"
542 case "bool":
543 return "[]byte(strconv.FormatBool(val))"
544 case "float32":
545 return "[]byte(strconv.FormatFloat(val, 'E', -1, 32))"
546 case "float64":
547 return "[]byte(strconv.FormatFloat(val, 'E', -1, 64))"
548 case "string":
549 return "[]byte(val)"
550 case "[]byte":
551 return "val"
552 }
553 return ""
554}
15func ByteStr(s string) ([]byte, error) {
16 msgStr := strings.Trim(s, "[]\n\r")
17 msgByteStr := strings.Split(msgStr, " ")
18 msgBytes := make([]byte, len(msgByteStr))
19 for i := range msgBytes {
20 b, err := strconv.Atoi(msgByteStr[i])
21 if err != nil {
22 return msgBytes[:i], err
23 }
24 msgBytes[i] = byte(b)
25 }
26 return msgBytes, nil
27}
27func toByteBool(b bool) byte {
28 if b {
29 return byte(0x01)
30 }
31 return byte(0x00)
32}
51func bcd2str(x uint16) string {
52 if (x>>12)&15 != 0 {
53 return fmt.Sprintf("%d%d.%d%d", (x>>12)&15, (x>>8)&15, (x>>4)&15, (x>>0)&15)
54 } else {
55 return fmt.Sprintf("%d.%d%d", (x>>8)&15, (x>>4)&15, (x>>0)&15)
56 }
57}

Related snippets