Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: first 5 bits and last 3 bits

by ikegami (Patriarch)
on Jul 26, 2011 at 18:55 UTC ( [id://916823]=note: print w/replies, xml ) Need Help??


in reply to first 5 bits and last 3 bits

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.

Replies are listed 'Best First'.
Re^2: first 5 bits and last 3 bits
by pashanoid (Scribe) on Jul 27, 2011 at 06:15 UTC
    thank you so much for the answer and education!!!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://916823]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-04-19 11:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found