Exemplo n.º 1
0
def dec_to_bcd_8421(num):
    """Convert a decimal to binary, and decompress into Binary Coded Decimal.
    Adds trailing bits to the left to enforce a 4-bit "nibble" on all digits.
    Uses 8421 notation [see wikipedia.org/wiki/Binary-coded_decimal]"""
    bcd, binary, decimals = '', '', ''
    for digit in str(num):
        binval = encoders.dec_to_bin(int(digit))
        binary += '{}{}'.format(binval, ' ' * (4 - len(binval) + 1))
        if len(binval) < 4:
            binval = binval.zfill(4)
        bcd += '{} '.format(binval)
        decimals += digit + (' ' * 4)
    _show_bcd(num, decimals, binary, bcd)
    return bcd
Exemplo n.º 2
0
def dec_to_bcd_excess3(num, bias=3):
    """Converts a binary to Binary Coded Decimal, then converts again to
    excess-3 BCD, which has a 'bit bias' of `bias`, where bits are
    shifted by the given bias. See wikipedia.org/wiki/Excess-3 for more."""
    bcd, binary, decimals = '', '', ''
    for digit in str(num):
        binval = encoders.dec_to_bin(int(digit))
        binval = BaseDataType.add(str(binval), bias)
        binary += '{}{}'.format(binval, ' ' * (4 - len(binval) + 1))
        if len(binval) < 4:
            binval = binval.zfill(4)
        bcd += '{} '.format(binval)
        decimals += digit + (' ' * 4)
    _show_bcd(num, decimals, binary, bcd)
    return bcd
Exemplo n.º 3
0
 def get_networkid(self, ip):
     """Network ID is comprised of Network Destination and Netmask,
     using CIDR notation. https://www.youtube.com/watch?v=t5xYI0jzOf4
     """
     entry = self[ip]
     mask = entry['network_mask']
     offset = 0
     # Add the octets as binary, then get the number of most significant
     # bits and add those to the end, to get the final CIDR encoded number.
     for octet in mask.split('.'):
         if octet == '255':
             offset += 8
         elif octet != '0':
             bits = encoders.dec_to_bin(int(octet))[0:4]
             for bit in bits:
                 if bit == '1':
                     offset += 1
     return '{}/{}'.format(entry['destination'], offset)
Exemplo n.º 4
0
def twos_complement(binary):
    """Conversion algorithm from
    cs.cornell.edu/~tomf/notes/cps104/twoscomp.html#twotwo"""
    old = binary
    binary = ones_complement(binary)
    ones = binary
    binary = BaseDataType.increment(''.join(binary))
    if DEBUG:
        print('Complements: one: {}, two: {}, (original: {})'.format(
            ''.join(ones), binary, ''.join(old)))
    dec = bin_to_dec(binary)
    sign, res = ('neg', -dec) if list(binary)[0] == '1' else (
        'pos',
        dec,
    )
    res_bin = dec_to_bin(res)
    if DEBUG:
        print('Final decimal is {}: {} ({})'.format(sign, res, res_bin))
    return res_bin