NicholasAdamou icon

Extra Credit (CSC-218)

NicholasAdamou | PRO | 10/28/19 04:08:02 PM UTC | 0 ⭐ | 286 👁️ | Never ⏰ | []
Python |

1.86 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""main.py - Extra Credit for CSC-218.
           - Convert a signed/unsigned decimal value into its binary & hex counter-parts.
 
@author: Nicholas Adamou
@date: 10/28/19
"""
 
# Short-hand for:
# 0 1 2 3 4 5 6 7 8 9 + A B C D E F
hex = [str(i) for i in range(10)] + ["A", "B", "C", "D", "E", "F"]
 
 
# Converts a decimal to its
# binary counter-part (unsigned).
def decimal2Binary(decimal):
    if decimal > 1:
        # Obtain the first binary bits, by
        # floor dividing the decimal value by 2.
        decimal2Binary(decimal // 2)
 
    # Print each binary representation of the decimal,
    # by taking the modulo of the decimal.
    print(decimal % 2, end='')
 
 
# Find the binary representation of a negative
# number.
def TwosComplement(decimal, n=8):
    # Convert the decimal into its negative counter-part,
    # through bit shifts and &.
    # e.g. -10 = -10 & ((2 * 2^8) - 1) = 511
    return decimal & (2 << n) - 1
 
 
# Convert a decimal value into its
# hexadecimal counter-part.
def hexa(decimal):
    s = ""
 
    # Loop while decimal exists.
    while decimal:
        # Obtain the first hex digit.
        s += hex[decimal % 16]
        # Cut the decimal by 16, by
        # floor dividing itself by 16.
        decimal //= 16
 
    # Correct the ordering of the hex value,
    # by reverse slicing the 's' value.
    return "0x" + s[::-1]
 
 
if __name__ == '__main__':
    decimal = 10  # Unsigned
 
    # Convert unsigned 'decimal' to BIN.
    decimal2Binary(decimal)
    print()
 
    # Convert unsigned 'decimal' to Hex.
    print(hexa(decimal))
 
    signed_decimal = TwosComplement(-decimal)  # Signed
 
    # Convert unsigned 'decimal' to BIN.
    decimal2Binary(signed_decimal)
    print()
 
    # Convert unsigned 'decimal' to Hex.
    print(hexa(signed_decimal))

Comments