github.com/zhongdalu/gf@v1.0.0/g/encoding/gbinary/gbinary_bits.go (about)

     1  // Copyright 2017 gf Author(https://github.com/zhongdalu/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/zhongdalu/gf.
     6  
     7  package gbinary
     8  
     9  // 实验特性
    10  
    11  // 二进制位(0|1)
    12  type Bit int8
    13  
    14  // 默认编码
    15  func EncodeBits(bits []Bit, i int, l int) []Bit {
    16  	return EncodeBitsWithUint(bits, uint(i), l)
    17  }
    18  
    19  // 将ui按位合并到bits数组中,并占length长度位(注意:uis数组中存放的是二进制的0|1数字)
    20  func EncodeBitsWithUint(bits []Bit, ui uint, l int) []Bit {
    21  	a := make([]Bit, l)
    22  	for i := l - 1; i >= 0; i-- {
    23  		a[i] = Bit(ui & 1)
    24  		ui >>= 1
    25  	}
    26  	if bits != nil {
    27  		return append(bits, a...)
    28  	} else {
    29  		return a
    30  	}
    31  }
    32  
    33  // 将bits转换为[]byte,从左至右进行编码,不足1 byte按0往末尾补充
    34  func EncodeBitsToBytes(bits []Bit) []byte {
    35  	if len(bits)%8 != 0 {
    36  		for i := 0; i < len(bits)%8; i++ {
    37  			bits = append(bits, 0)
    38  		}
    39  	}
    40  	b := make([]byte, 0)
    41  	for i := 0; i < len(bits); i += 8 {
    42  		b = append(b, byte(DecodeBitsToUint(bits[i:i+8])))
    43  	}
    44  	return b
    45  }
    46  
    47  // 解析为int
    48  func DecodeBits(bits []Bit) int {
    49  	v := int(0)
    50  	for _, i := range bits {
    51  		v = v<<1 | int(i)
    52  	}
    53  	return v
    54  }
    55  
    56  // 解析为uint
    57  func DecodeBitsToUint(bits []Bit) uint {
    58  	v := uint(0)
    59  	for _, i := range bits {
    60  		v = v<<1 | uint(i)
    61  	}
    62  	return v
    63  }
    64  
    65  // 解析[]byte为字位数组[]uint8
    66  func DecodeBytesToBits(bs []byte) []Bit {
    67  	bits := make([]Bit, 0)
    68  	for _, b := range bs {
    69  		bits = EncodeBitsWithUint(bits, uint(b), 8)
    70  	}
    71  	return bits
    72  }