my $byte = 129; # 0b10000001 = 129
my $most_significant_5 = $byte >> 3; # 0b10000 = 16
my $least_significant_3 = $byte & 0x7; # 0b 001 = 1
How did I arrive at that? Basically, you want to either
- Mask out the bits of higher significance than those you want, then shift the bits you want to index 0; or
- Shift the bits you want to index 0 then mask out the bits of higher significance than those you want.
is a simplification of
----------------------------------------------------
$byte >> 3 ( $byte & 0xFF ) >> 3 or ( $byte >> 3 ) & 0x1F
$byte & 0x7 ( $byte & 0x7 ) >> 0 or ( $byte >> 0 ) & 0x7
Notes;
- «0x7» is 0b111 or 23-1. «& 0x7» "keeps" only the least significant 3 bits.
- «0x1F» is 0b11111 or 25-1. «& 0x7» "keeps" only the least significant 5 bits.
- «0xFF» is 0b11111111 or 28-1. «& 0x7» "keeps" only the least significant 8 bits.
- «& 0xFF» is a no-op when dealing with 8-bit values.
- «>> 0» is a no-op for integers, which is what we're dealing with.