comp_deux.py

Created by pascal-chauvin

Created on September 24, 2020

1.04 KB

Calcul du complément à 2**n, sur n bits.


def conv_n_vers_base(n, base=2):
  """
    Convertit l'entier naturel n vers la base 'base'.

    >>> conv_n_vers_base(9)
    [1, 0, 0, 1]

    >>> conv_n_vers_base(100, 4)
    [1, 2, 1, 0]
  """

  b=[]
  while n>0:
    b=[n%base]+b
    n=n//base
  if len(b)==0:
    b.append(0)
  return b


def conv_base_vers_10(chiffres, base=2):
  """
    Convertit l'entier naturel donné par la liste de ses chiffres 
    dans la base 'base'.

    >>> conv_base_vers_10([1, 0, 0, 1], 2)
    9

    >>> conv_base_vers_10([1, 2, 1, 0], 4)
    100
  """

  n = 0
  for i in range(len(chiffres)):
    n = n*base + chiffres[i]
  return n


def complement_a_deux(x, n):
  """
    Calcule le complément à (2**n) du nombre entier x, 
    représenté sur n bits.

    >>> complement_a_deux(3, 3)
    5

    >>> complement_a_deux(3, 4)
    13

    >>> complement_a_deux(3, 8)
    253
  """

  bits = conv_n_vers_base(x)
  while len(bits) < n:
    bits = [0] + bits

  for i in range(len(bits)):
    bits[i] = 1 - bits[i]

  return (conv_base_vers_10(bits) + 1)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.