Is 0b11111110 equal to -1 (ones' complement), or is 0b11111110 equal to -2 (two's complement)?

The latter is what computers now use universally. The format is very convenient for computers because the same circuitry can be used for both signed and unsigned additions and subtractions.

6 as 8-bit unsigned = 00000110 = 6 as 8-bit 2's comp 226 as 8-bit unsigned = 11100010 = -30 as 8-bit 2's comp + -------- 232 as 8-bit unsigned = 11101000 = -24 as 8-bit 2's comp

You seem to suggest ones' complement, but I'm going to assume it's two's complement since that's far more likely.

To cast the number from unsigned to signed, you can use any of the following:

my $x = 0b11100010; # 226 $x = -( ( ~$x + 1 ) & 0xFF ) if $x & 0x80; -or- $x -= 0x100 if $x >= 0x80; -or- $x = unpack('c', pack('C', $x)); say $x; # -30

~x + 1 negates a two's complement integer, so the first solution converts the number to its positive counterpart, which we then negate using unary-minus.

The second solution takes advantage of Perl's ability to work with integers larger than 8-bits in size.

If you started with a string of bytes, you could use unpack 'c' from the start to avoid having to perform this cast.


In reply to Re: Flipping partial bits by ikegami
in thread Flipping partial bits by rickss

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.