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