Home > Blockchain >  How to convert a slice of a byte array to a uint32 value
How to convert a slice of a byte array to a uint32 value

Time:10-26

I am unable to convert a slice of a byte array to a uint value. I have seen that passing in slices to functions is a more idiomatic way to go but I have the following problems:

  1. Print only a single element from the slice (it prints [102] instead of 102) basically printing it as a byte array instead of a byte
  2. Convert a slice of the byte array (1 element) to a uint32 (binary.BigEndian.Uint32 seems to work for the whole array but not just a single element in the array)
  3. Convert a slice of the byte array (1 element) to a byte
  4. Cast a slice of the byte array (1 element) to a uint32 variable

I have included the errors as comments below. The compiler gives the error as to why, but how do I cast/convert from these slices to a variable?

Below is the code:

package main

import (
    "encoding/binary"
    "fmt"
)

const FrameBitsIV =  0x10  

func main() {
    // str := "ab£"
    data := []byte{102, 97, 108, 99, 111, 110}
    uint_value := []uint8{1, 2, 3, 4, 5}
    x := data[0:]
    
    fmt.Println(x)
     
    pass_slice(data[0:], uint_value[0:])

}

func pass_slice(buf []byte, uint_value []uint8) {
    x := buf[0:1]
    fmt.Println(x) //prints [102]
    y := binary.BigEndian.Uint32(x)
    fmt.Println(y) //prints error
    var z byte = buf[0:1] //cannot use buf[0:1] (value of type []byte) as byte value in variable declaration
    u := uint32(buf[0:]) //cannot convert buf[0:] (value of type []byte) to uint32

}

Thank you so much.

CodePudding user response:

  • Print only a single element from the slice:
  • Convert a slice of the byte array (1 element) to a byte

Use an index expression to get an element of the byte slice as a byte:

x := buf[0]    // x is type byte
fmt.Println(x) //prints 102
  • Convert a slice of the byte array (1 element) to a uint32.
  • Cast a slice of the byte array (1 element) to a uint32 variable

Use an index expression to get the byte and convert to uint32:

x := uint32(buf[0]) // x is type uint32
fmt.Println(x) //prints 102

Note the difference between the index expressions used in this answer and the slice expressions used in the question.

  • Related