type Encoder struct { to []byte lo uint32 hi uint32 } func NewEncoder() *Encoder { return &Encoder{ hi: ^uint32(0), } } func (e *Encoder) WriteBit(probability1 uint16, is1 bool) { var ( diff = uint64(e.hi - e.lo) prob = uint64(probability1) add = diff * prob >> 16 mid = e.lo + uint32(add) ) if is1 { e.lo = mid + 1 } else { e.hi = mid } for e.lo^e.hi <= 0x_ff_ff_ff { b := byte(e.lo >> 24) e.to = append(e.to, b) e.lo <<= 8 e.hi <<= 8 e.hi += 0xff } } func (e *Encoder) Bytes() []byte { var ( b1 = byte(e.lo >> 24) b2 = byte(e.lo >> 16) b3 = byte(e.lo >> 8) b4 = byte(e.lo) ) return append( e.to, b1, b2, b3, b4, ) }
To receive a hint, submit unfixed code.