python binary bitwise operation - ghdrako/doc_snipets GitHub Wiki

Bitwise operation are use to change or combine one or more binary numbers

z = x AND y  // &
z = x OR y  // |
z = x XOR y // ^
z = NOT x  // ~
z = x << n  // shiftx bits in x on left n position

5<<2
20
101 << 2 daje 10100 = 16+4 = 20


z = xx >> n // shiftx bits in x on right n position

Allow:

  • manipulate flags
  • access to portion of number
  • manipulate raw binary data

Binary number - comon bases:

  • decimal (42)
  • binary (0b0101010 = 42)
  • octal (0o52 = 42)
  • hex (0x2A = 42)
>>> x = 42
>>> f"{x:b}
'101010'
>>> f"{x:b08}
'00101010'
>>> oct(x)
0o52
>>> hex(x)
0x2A
>>> bin(x)
0b0101010

Negative number representation

Two's compliment - used by python

  • remove problem of ambiguous zero
  • use the left-most bit to indicate positive or negative
  • negative number are stored as their complement plus 1
  • asymmetrical representation
    • more negative number are avaliable then positive
    • 8-bit two's complement ranges from -128(10) - 127(10)
0000 0000            => 0(10)
0000 0001            => 1(10)
1111 1111            => -1(10)
0000 0110            => 6(10)
~ 0000 0110 = 1111 1001 => -7(10)
>>> ~9
-10


0000 1001 (9)
1111 0110 (~9)
def twos(val_str, bytes):
    import sys
    val = int(val_str, 2)
    b = val.to_bytes(bytes, byteorder=sys.byteorder, signed=False)                                                          
    return int.from_bytes(b, byteorder=sys.byteorder, signed=True)

Check:

twos('11111111', 1)  # gives -1
twos('01111111', 1)  # gives 127

In python with bin function or format - binary numbers are represented unsigned, and negative numbers have a "-" prefix, just like they do in decimal. You lose the ability to specify a negative number using its two's complement representation, but remember that two's complement is a storage implementation detail, not a proper indication of the underlying value itself. There's less confusion and the user isn't required to understand the storage details.

>>> bin(-7)
'-0b111'
>>> bin(7)
'0b111'
>>> bin(~0b0110)   // ~6
-0b111             // -7  # zaprzeczenie 6 daje zgodnie z 2 complimentary -7   pokazuje 7 i znak ~00110  11001 +1 = 11010 ( internal reprezentation ~6 czyli -7) ale python python operacje na integer wykonuje na liczbach 8-bajtowych(64 bity) ~0000...0110 wyswietla jako wartosc unsign czyli 7 => 0b111 i dodaje znak - czyli -0b111

https://stackoverflow.com/questions/12946116/twos-complement-binary-in-python

Integer

Python has two types of integers that it seamlessly switch between:

  • Fixed precision , typicaly 8 bytes
  • Arbitrary precision , limitless size , bignum implementation

Python integers isn't unsigned. Python does not have unsigned integer.

Floating point

Floating point number are aproximation

Fixed point

Python's decimal.Decimal object is fixed point. Good for represent money. Fixed point values store digits to specified precision. CPU is not optimalized for that.