Created
November 6, 2016 10:54
-
-
Save TuxCoding/790f50452860d70b720b6f2fefcd4a27 to your computer and use it in GitHub Desktop.
Converts an integer to a binary with two_complement and unsigned representation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/python3 | |
| # Example output: | |
| # Enter a number:1024 | |
| # Number: 1024 | |
| # Needed bits: 11 | |
| # Bytes (unsigned) 100 0000 0000 | |
| # Bytes (two-complement) 0100 0000 0000 | |
| BYTE_SIZE = 4 | |
| def align(word, number): | |
| return "{:<50s}{:>50s}".format(word, number) | |
| def binary_format(binary): | |
| # Remove the binary identifier | |
| clean = binary[2:] | |
| result = "" | |
| for i in range(1, len(clean) + 1): | |
| result = clean[len(clean) - i] + result | |
| if i % BYTE_SIZE == 0: | |
| result = " " + result | |
| return result | |
| def two_complement(number): | |
| bits = number.bit_length() | |
| binary = bin(number % (1 << (bits + 1))); | |
| if number > 0: | |
| # Add a leading zero | |
| binary = "0b0" + binary[2:] | |
| return binary; | |
| user_input = input("Enter a number:") | |
| input_number = int(user_input) | |
| bits = input_number.bit_length() | |
| print("Number:", input_number) | |
| print("Needed bits:", bits) | |
| print(align('Bytes (unsigned)', binary_format(bin(input_number)))) | |
| print(align('Bytes (two-complement)', binary_format(two_complement(input_number)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment