gbinary_bit.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gbinary
  7. // NOTE: THIS IS AN EXPERIMENTAL FEATURE!
  8. // 二进制位(0|1)
  9. type Bit int8
  10. // 默认编码
  11. func EncodeBits(bits []Bit, i int, l int) []Bit {
  12. return EncodeBitsWithUint(bits, uint(i), l)
  13. }
  14. // 将ui按位合并到bits数组中,并占length长度位(注意:uis数组中存放的是二进制的0|1数字)
  15. func EncodeBitsWithUint(bits []Bit, ui uint, l int) []Bit {
  16. a := make([]Bit, l)
  17. for i := l - 1; i >= 0; i-- {
  18. a[i] = Bit(ui & 1)
  19. ui >>= 1
  20. }
  21. if bits != nil {
  22. return append(bits, a...)
  23. } else {
  24. return a
  25. }
  26. }
  27. // 将bits转换为[]byte,从左至右进行编码,不足1 byte按0往末尾补充
  28. func EncodeBitsToBytes(bits []Bit) []byte {
  29. if len(bits)%8 != 0 {
  30. for i := 0; i < len(bits)%8; i++ {
  31. bits = append(bits, 0)
  32. }
  33. }
  34. b := make([]byte, 0)
  35. for i := 0; i < len(bits); i += 8 {
  36. b = append(b, byte(DecodeBitsToUint(bits[i:i+8])))
  37. }
  38. return b
  39. }
  40. // 解析为int
  41. func DecodeBits(bits []Bit) int {
  42. v := 0
  43. for _, i := range bits {
  44. v = v<<1 | int(i)
  45. }
  46. return v
  47. }
  48. // 解析为uint
  49. func DecodeBitsToUint(bits []Bit) uint {
  50. v := uint(0)
  51. for _, i := range bits {
  52. v = v<<1 | uint(i)
  53. }
  54. return v
  55. }
  56. // 解析[]byte为字位数组[]uint8
  57. func DecodeBytesToBits(bs []byte) []Bit {
  58. bits := make([]Bit, 0)
  59. for _, b := range bs {
  60. bits = EncodeBitsWithUint(bits, uint(b), 8)
  61. }
  62. return bits
  63. }