in reply to Flipping partial bits

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.