NicholasAdamou

Extra Credit (CSC-218)

Oct 28th, 2019
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """main.py - Extra Credit for CSC-218.
  4.           - Convert a signed/unsigned decimal value into its binary & hex counter-parts.
  5.  
  6. @author: Nicholas Adamou
  7. @date: 10/28/19
  8. """
  9.  
  10. # Short-hand for:
  11. # 0 1 2 3 4 5 6 7 8 9 + A B C D E F
  12. hex = [str(i) for i in range(10)] + ["A", "B", "C", "D", "E", "F"]
  13.  
  14.  
  15. # Converts a decimal to its
  16. # binary counter-part (unsigned).
  17. def decimal2Binary(decimal):
  18.     if decimal > 1:
  19.         # Obtain the first binary bits, by
  20.         # floor dividing the decimal value by 2.
  21.         decimal2Binary(decimal // 2)
  22.  
  23.     # Print each binary representation of the decimal,
  24.     # by taking the modulo of the decimal.
  25.     print(decimal % 2, end='')
  26.  
  27.  
  28. # Find the binary representation of a negative
  29. # number.
  30. def TwosComplement(decimal, n=8):
  31.     # Convert the decimal into its negative counter-part,
  32.     # through bit shifts and &.
  33.     # e.g. -10 = -10 & ((2 * 2^8) - 1) = 511
  34.     return decimal & (2 << n) - 1
  35.  
  36.  
  37. # Convert a decimal value into its
  38. # hexadecimal counter-part.
  39. def hexa(decimal):
  40.     s = ""
  41.  
  42.     # Loop while decimal exists.
  43.     while decimal:
  44.         # Obtain the first hex digit.
  45.         s += hex[decimal % 16]
  46.         # Cut the decimal by 16, by
  47.         # floor dividing itself by 16.
  48.         decimal //= 16
  49.  
  50.     # Correct the ordering of the hex value,
  51.     # by reverse slicing the 's' value.
  52.     return "0x" + s[::-1]
  53.  
  54.  
  55. if __name__ == '__main__':
  56.     decimal = 10  # Unsigned
  57.  
  58.     # Convert unsigned 'decimal' to BIN.
  59.     decimal2Binary(decimal)
  60.     print()
  61.  
  62.     # Convert unsigned 'decimal' to Hex.
  63.     print(hexa(decimal))
  64.  
  65.     signed_decimal = TwosComplement(-decimal)  # Signed
  66.  
  67.     # Convert unsigned 'decimal' to BIN.
  68.     decimal2Binary(signed_decimal)
  69.     print()
  70.  
  71.     # Convert unsigned 'decimal' to Hex.
  72.     print(hexa(signed_decimal))
Advertisement
Add Comment
Please, Sign In to add comment