github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bit/reverse.go (about)

     1  package bit
     2  
     3  func Reverse(x uint64, width uint) (rx uint64) {
     4  	switch width {
     5  	case 1, 2, 3, 4, 5, 6, 7:
     6  		return uint64(reverseByte[x] >> (8 - width))
     7  	case 8:
     8  		return uint64(reverseByte[byte(x)])
     9  	case 16:
    10  		return uint64(reverseByte[byte(x)])<<8 | uint64(reverseByte[byte(x>>8)])
    11  	case 24:
    12  		return uint64(reverseByte[byte(x)])<<16 | uint64(reverseByte[byte(x>>16)]) | uint64(reverseByte[byte(x>>8)])<<8
    13  	case 32:
    14  		return uint64(reverseByte[byte(x)])<<24 | uint64(reverseByte[byte(x>>8)])<<16 | uint64(reverseByte[byte(x>>16)])<<8 | uint64(reverseByte[byte(x>>24)])
    15  	}
    16  	return slowReverse(x, width)
    17  }
    18  
    19  // slow version
    20  func slowReverse(x uint64, width uint) (rx uint64) {
    21  	for i := uint(0); i < width; i += 1 {
    22  		rx = (rx << 1) | x&1
    23  		x >>= 1
    24  	}
    25  	return
    26  }