-1

I am having trouble in achieving either of the following in Python:

  1. Convert a Decimal value to Binary signed 2's complement. Examples:

    40975 = 00000000000000001010000000001111
    
    275 = 0000000100010011
    
  2. Convert a Binary value to Binary signed 2's complement. Examples:

    1010000000001111 = 00000000000000001010000000001111
    
    100010011 = 0000000100010011
    

Does anyone know of the easiest way of achieving this in Python?

  • I think these fits for you question https://stackoverflow.com/questions/10080559/convert-a-decimal-string-to-a-signed-2s-complement-binary-integer –  Jan 12 '20 at 15:26
  • Thanks but I don't think that post helps me. It seems to talk more about getting a hexadecimal notation. I may be missing something but I fail to find what I need from that post :/ – Ivan Dackovic Jan 12 '20 at 15:44

1 Answers1

0

I found the solution, below is the explanation of what I did.

I needed to do the following:

1) Determine the length of the binary value:

2) Determine the smallest power of 2 greater than that the length output, then add 0's to the left of the binary output until the length matches that returned smallest power of 2 value.

A few of the solutions for the above can be found on this excellent thread Find the smallest power of 2 greater than n in Python. Here are the three of the functions I've tried:

len_1 = 16
len_2 = 9

def next_power_of_2_ver_1(x):  
    return 1 if x == 0 else 2**(x).bit_length()

Output:
32
16


def next_power_of_2_ver_2(x):
    return 1 if x == 0 else 2**math.ceil(math.log2(x + 1))

Output:
32
16


def next_power_of_2_ver_3(x):
    return 1<<(x).bit_length()

Output:
32
16

I have settled on the following solution:

def next_power_of_2_ver_3(x):
    return 1<<(x).bit_length()

Though this is a part of a larger code that I have, the operation that achieves what I need is as follows:

import math

# this function returns the smallest power of 2 greater than the binary output length so that we may get Binary signed 2's complement
def next_power_of_2(x): 
    return 1<<(x).bit_length()

decimal_value = "40975"

# convert the decimal value to binary format and remove the '0b' prefix
binary_value = bin(int(decimal_value))[2:] 
Output: 1010000000001111

# determine the length of the binary value
binary_value_len = len(binary_value) 
Output: 16

# use function 'next_power_of_2' to return the smallest power of 2 greater than the binary output length
power_of_2_binary_value_len = next_power_of_2(binary_value_len) 
Output: 32

# determine the amount of '0's we need to add to the binary result
calc_leading_0 = power_of_2_binary_value_len - binary_value_len
Output: 16

# adds the leading zeros thus completing the binary signed 2's complement formula
binary_signed_2s_binary_value = (binary_value).zfill(binary_value_len + calc_leading_0) 
Output: 00000000000000001010000000001111