gbinary_bit.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright GoFrame Author(https://goframe.org). 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. // Bit Binary bit (0 | 1)
  9. type Bit int8
  10. // EncodeBits does encode bits return bits Default coding
  11. func EncodeBits(bits []Bit, i int, l int) []Bit {
  12. return EncodeBitsWithUint(bits, uint(i), l)
  13. }
  14. // EncodeBitsWithUint . Merge ui bitwise into the bits array and occupy the length bits
  15. // (Note: binary 0 | 1 digits are stored in the uis array)
  16. func EncodeBitsWithUint(bits []Bit, ui uint, l int) []Bit {
  17. a := make([]Bit, l)
  18. for i := l - 1; i >= 0; i-- {
  19. a[i] = Bit(ui & 1)
  20. ui >>= 1
  21. }
  22. if bits != nil {
  23. return append(bits, a...)
  24. }
  25. return a
  26. }
  27. // EncodeBitsToBytes . does encode bits to bytes
  28. // Convert bits to [] byte, encode from left to right, and add less than 1 byte from 0 to the end.
  29. func EncodeBitsToBytes(bits []Bit) []byte {
  30. if len(bits)%8 != 0 {
  31. for i := 0; i < len(bits)%8; i++ {
  32. bits = append(bits, 0)
  33. }
  34. }
  35. b := make([]byte, 0)
  36. for i := 0; i < len(bits); i += 8 {
  37. b = append(b, byte(DecodeBitsToUint(bits[i:i+8])))
  38. }
  39. return b
  40. }
  41. // DecodeBits .does decode bits to int
  42. // Resolve to int
  43. func DecodeBits(bits []Bit) int {
  44. v := 0
  45. for _, i := range bits {
  46. v = v<<1 | int(i)
  47. }
  48. return v
  49. }
  50. // DecodeBitsToUint .Resolve to uint
  51. func DecodeBitsToUint(bits []Bit) uint {
  52. v := uint(0)
  53. for _, i := range bits {
  54. v = v<<1 | uint(i)
  55. }
  56. return v
  57. }
  58. // DecodeBytesToBits .Parsing [] byte into character array [] uint8
  59. func DecodeBytesToBits(bs []byte) []Bit {
  60. bits := make([]Bit, 0)
  61. for _, b := range bs {
  62. bits = EncodeBitsWithUint(bits, uint(b), 8)
  63. }
  64. return bits
  65. }