Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Flipping partial bits

by haukex (Archbishop)
on Nov 12, 2020 at 19:46 UTC ( [id://11123621]=note: print w/replies, xml ) Need Help??


in reply to Flipping partial bits

but I can't quite get right the flipping of the remaining 7 bits

I agree with dave_the_m that some more examples would be best. But to answer this part of the question, you can mask the value to only get the lower 7 bits with $val & 0x7F, and then flip the lower 7 bits with an XOR, i.e. $val ^ 0x7F, put together that's my $y = ($x & 0x7F)^0x7F;.

$z = $x & (1 << 7);

BTW, since you're probably just looking to get a true/false value from this, you don't need the bit shift: $x & 0x80 is enough to tell you if the high bit is set or not, since the return value will be either 0 (false) or 0x80 (true). Update: Actually, never mind - the compiler is of course smart enough to optimize (1 << 7) into 128. I personally prefer 0x80 or 0b1000_0000 over (1 << 7), which is why I tripped over this at first, but TIMTOWTDI.

Replies are listed 'Best First'.
Re^2: Flipping partial bits
by jszinger (Scribe) on Nov 13, 2020 at 16:26 UTC
    The high bit does not need to be masked. Something like:
    for my $x (0..0xff) { my $y = ( $x & 0x80 ) ? -($x ^ 0xff) : $x; say "$x $y" }
      The high bit does not need to be masked.

      Yes, that's true, though I felt the specs were a little bit lacking (hence my request for more examples), which is why I played it safe and showed how to do the masking too.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-19 15:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found