标签云

微信群

扫码加入我们

WeChat QR Code

How can i declare a bit(binary) and append more bits to it later on for GO language. The size of the bits is dynamic base on the number of bits that will be appended to it. Then once finished appending the bits i want to convert those bits into a Byte or BytesI see examples online for declaring int then converting it to binary then doing logical operations to it like OR AND etc.. But this won't do because i don't know the size that i need to declare for the int. var a uint8 = 0a |= 196fmt.Printf(“%b”, a)// prints 11000100I want something like this. var data2 bit = 0data2 = append(data2,1)data2 = append(data2,0)data2 = append(data2,0)fmt.Printf("%b\n", data2) Output would be "0100" in binary later on i can convert it to byte


If you are looking for and arbitrary length bitvector: Google for it. If you need more than 64 bits you need to resort to an external package and question seeking such are OT on SO.

2019年04月25日55分58秒

If 64 bits are enough for you, easiest is to use uint64. If not, you have to use a []byte (or some other slice). Additionally you have to keep track of the number of bits added. Are you having problem doing this? Also there are 3rd party libs for this, e.g. github.com/icza/bitio (disclosure: I'm the author).

1970年01月01日00分06秒

For reference, the bitwise an shift operators are listed here: golang.org/ref/spec#Arithmetic_operators. If the end result is always going to be a byte, then you only need to start with a byte.

2019年04月25日55分58秒