A single 1 byte could be from 0
to 255
. I intend to rescale it to be from 0
to 7
. I have done this:
bit8 := uint8(136)
// To re-scale 1 byte from 0 to 2^3-1 i.e. 0 to 7
bit3 := bit8 / 0xff * 0b0111
The resulting bit3
is 0
, but I expect it to be 3
or 4
depending upon rounding down or up. Since the floating point exact value would be 136/255*7 = 3.733333333
.
How can I achieve my desired output? Rounding up and down doesn't matter at this point. Whatever is convenient is fine.
I want the operation to be as efficient as possible. Because it's going to be done inside a loop. So, the solutions like below are not optimal:
bit8 := uint8(136)
// To re-scale 1 byte from 0 to 2^3-1 i.e. 0 to 7
bit3 := uint8(float64(bit8) / 255.0 * 7.0)
Take the top 3 bits of the byte (this rounds down):
bit3 := bit8 >> 5