Bitwise not for Converting from two's complement representation

Hi, I’m trying to replicate a kodular procedure similar to this in python to take a negative number and make it a two’s complement. However I have problems with the ~ (bitwise not) operation since I can’t find a block in Kodular that does it, is there a way or is it necessary to do it in a separate procedure ?. Or better yet, is there a way to represent a negative number in Kodular using the two’s complement format?

indent preformatted text by 4 spaces

def twos_complement(input_value: int, num_bits: int) -> int:
“”“Calculates a two’s complement integer from the given input value’s bits.”""
mask = 2 ** (num_bits - 1)
return -(input_value & mask) + (input_value & ~mask)
indent preformatted text by 4 spaces

I didn’t understand, can you explain in simple langauge?

thanks in essence I needed to convert a number in complement to two, I found this solution that worked for me, thanks for the answer.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.