如何用索引构造一个翻转的单比特位域?

What's the most efficient way to construct a flipped single bit bitfields given an input index?

For example:

input: 0 output: 100000000000
input: 1 output: 010000000000
input: 2 output: 001000000000
input: 9 output: 000000000100

You're looking for the right shift operator, which shifts each bit in its left operand to the right as many times as specified by the right operand.

x >> y // Shifts each bit in "x" to the right "y" times.

To display bitfields as in your example you'll want to use a left operand with only the leftmost bit set, then shift right the number of times as given, and use the %b printf directive to get a binary string, for example (Go Playground):

func setbit16(idx uint8) string {
  return fmt.Sprintf("%016b", uint16(0x8000)>>idx)
}

func main() {
  xs := []uint8{0, 1, 2, 9, 15, 20}
  for _, x := range xs {
    fmt.Printf("%2d -> %q
", x, setbit16(x))
  }
  //  0 -> "1000000000000000"
  //  1 -> "0100000000000000"
  //  2 -> "0010000000000000"
  //  9 -> "0000000001000000"
  // 15 -> "0000000000000001"
  // 20 -> "0000000000000000"
}

Of course, if you just want the resulting number and not necessarily to display the bitfield then you can just use the operator (or the left shift version):

uint16(0x8000) >> 2 // => 0b0010000000000000
uint16(0x0001) << 2 // => 0b0000000000000100