我如何从一个字节中获取比特的子集?

I have a byte 0x38

b:= 0x38
fmt.Printf("%b
",b)

Which is 00111000 in binary.

How can i get a subset of this as a new int? For exampe i want bit 7,6,5 which in this case will be int(1). Or bit 3,2,1 which will be int(4)

A more generic approach that would allow you to pick unordered bits would be something like:

// subset has to go from lowest to highest
func bits(b uint, subset ...uint) (r uint) {
    i := uint(0)
    for _, v := range subset {
        if b&(1<<v) > 0 {
            r = r | 1<<uint(i)
        }
        i++
    }
    return
}

func main() {
    fmt.Println(bits(0x38, 5, 6, 7), "x", 0x38>>5)
    fmt.Println(bits(0x38, 2, 4, 5))
    fmt.Println(bits(0x38, 1, 2, 3), "x", (0x38>>1)&7)
}

Keep in mind that for an sequential subset, @Guffa's solution is much faster.

To get the upper bits you can shift the value to the right

bits765 := b >> 5

To get bits in the middle you can shift them and then mask off unwanted bits:

bits321 := (b >> 1) & 7