How do i get a subset of bits from a byte?

huangapple go评论116阅读模式
英文:

How do i get a subset of bits from a byte?

问题

我有一个字节 0x38

  1. b:= 0x38
  2. fmt.Printf("%b\n",b)

它的二进制表示是 00111000。

我如何将其作为一个新的整数获取其中的一个子集?
例如,我想要获取第 7、6、5 位,这将是整数 1。
或者获取第 3、2、1 位,这将是整数 4。

英文:

I have a byte 0x38

  1. b:= 0x38
  2. fmt.Printf("%b\n",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)

答案1

得分: 3

要获取高位,您可以将值向右移动。

  1. bits765 := b >> 5

要获取中间的位,您可以将它们向右移动,然后屏蔽掉不需要的位:

  1. bits321 := (b >> 1) & 7
英文:

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

  1. bits765 := b >> 5

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

  1. bits321 := (b >> 1) & 7

答案2

得分: 3

一个更通用的方法,允许你选择无序的位,可以像这样实现:

  1. // subset 必须按照从低到高的顺序排列
  2. func bits(b uint, subset ...uint) (r uint) {
  3. i := uint(0)
  4. for _, v := range subset {
  5. if b&(1<<v) > 0 {
  6. r = r | 1<<uint(i)
  7. }
  8. i++
  9. }
  10. return
  11. }
  12. func main() {
  13. fmt.Println(bits(0x38, 5, 6, 7), "x", 0x38>>5)
  14. fmt.Println(bits(0x38, 2, 4, 5))
  15. fmt.Println(bits(0x38, 1, 2, 3), "x", (0x38>>1)&7)
  16. }

请注意,对于连续的子集,@Guffa 的解决方案速度更快。

英文:

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

  1. // subset has to go from lowest to highest
  2. func bits(b uint, subset ...uint) (r uint) {
  3. i := uint(0)
  4. for _, v := range subset {
  5. if b&amp;(1&lt;&lt;v) &gt; 0 {
  6. r = r | 1&lt;&lt;uint(i)
  7. }
  8. i++
  9. }
  10. return
  11. }
  12. func main() {
  13. fmt.Println(bits(0x38, 5, 6, 7), &quot;x&quot;, 0x38&gt;&gt;5)
  14. fmt.Println(bits(0x38, 2, 4, 5))
  15. fmt.Println(bits(0x38, 1, 2, 3), &quot;x&quot;, (0x38&gt;&gt;1)&amp;7)
  16. }

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

huangapple
  • 本文由 发表于 2014年9月27日 06:55:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/26069447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定