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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|