Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python convert integer to signed base 2 complement

def twos_comp(val, bits):
    """compute the 2's complement of int value val"""
    if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
        val = val - (1 << bits)        # compute negative value
    return val                         # return positive value as is
  
binary_string = '1010101010' # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))
Comment

PREVIOUS NEXT
Code Example
Python :: how to select number by twos in a list python next to each 
Python :: propositional logic python 
Python :: python for loop inside list 
Python :: how to get value_counts() order 
Python :: Get git sha 
Python :: Parallel Tasks python 
Python :: pyplot histogram labels in center 
Python :: customize path in url 
Python :: how to change color of square in pygame with keypress 
Python :: function TBone() if 2=2 then print("Sup") end 
Python :: gnuplot sum over a column 
Python :: santhal paragana 
Python :: ist comperension python 
Python :: check stl file for errors in pyvista 
Python :: how to use list compression with conditional formatting 
Python :: how to upgrade pip 
Shell :: remove angular cli 
Shell :: check supervisord status 
Shell :: Zsh is not installed. Please install zsh first. 
Shell :: dotnet ef not found 
Shell :: purge from terminal 
Shell :: install openzeppline 
Shell :: remove remote origin github 
Shell :: dns flush 
Shell :: cond install opencv 
Shell :: conda install xlrd 
Shell :: ubuntu command ram info 
Shell :: find text terminal filees 
Shell :: flush dns bash 
Shell :: test apache config 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =