Created
January 21, 2014 16:32
-
-
Save tejainece/8543345 to your computer and use it in GitHub Desktop.
Binary multiplication
This file contains 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
from math import ceil, log | |
def shift_and_sign_extend(num_list, shift=1): | |
length = 0 | |
#find the length | |
for index, element in enumerate(numlist): | |
tEl = element + '0' * (index * shift) | |
tLen = len(tEl) | |
numlist[index] = tEl | |
if length < tLen: | |
length = tLen | |
#extra bits required due to N operand addition | |
length += int(ceil(log(len(numlist)))) | |
#fix the sign extension | |
for index, element in enumerate(numlist): | |
if element[0] == "1": | |
numlist[index] = "1" * (length - len(element)) + element | |
else: | |
numlist[index] = "0" * (length - len(element)) + element | |
return (numlist, length) | |
def add_binary_string(num_list): | |
length = len(num_list[0]) | |
count = 0 | |
out = "" | |
for index in range(length): | |
for line_index, line in enumerate(numlist): | |
if line[-index-1] == "1": | |
count += 1 | |
if count % 2 == 1: | |
out = "1" + out | |
else: | |
out = "0" + out | |
count = count >> 1 | |
return out | |
def signedBinString2Int(num, bit_length): | |
if len(num) > bit_length: | |
num = num[-bit_length:] | |
out = 0 | |
if len(num) == bit_length and num[0] == "1": | |
out = int(num, 2) - (2**bit_length) | |
else: | |
out = int(num, 2) | |
return out | |
def gen_prod_string(numA, numB): | |
prod_strings = [] | |
lenB = len(numB) | |
for index, element in enumerate(numA[::-1]): | |
if element == "1": | |
prod_strings.append(numB) | |
else: | |
prod_strings.append("0" * lenB) | |
return prod_strings | |
numlist = gen_prod_string("0010", "1101") | |
#numlist = ["0111", "11111", "111", "1111"] | |
#add_binary_string(numlist, 2) | |
numlist,_ = shift_and_sign_extend(numlist, 1) | |
out = add_binary_string(numlist) | |
for index, element in enumerate(numlist): | |
print element, " ", signedBinString2Int(element, len(element)) | |
print '-' * len(numlist[0]) | |
print out, signedBinString2Int(out, len(out)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment