Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert negative integer value to hex in python

I use python 2.6

>>> hex(-199703103) '-0xbe73a3f'  >>> hex(199703103) '0xbe73a3f' 

Positive and negative value are the same?

When I use calc, the value is FFFFFFFFF418C5C1.

like image 735
nic nic Avatar asked Oct 19 '11 14:10

nic nic


People also ask

How do you convert a negative number to hexadecimal?

The hexadecimal value of a negative decimal number can be obtained starting from the binary value of that decimal number positive value. The binary value needs to be negated and then, to add 1. The result (converted to hex) represents the hex value of the respective negative decimal number.

How do you convert int to hex in Python?

hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.

How do you convert a negative number in Python?

In Python, positive numbers can be changed to negative numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive. However, when -abs () is used, then a positive number can be changed to a negative number.

Can an integer value be negative in Python?

All the negative and positive numbers along with 0 comprise integers. Thus, the numbers that are greater than 0 are positive, whole numbers lesser than 0 are referred to as negative. This is the concept used in Python is negative program.


1 Answers

Python's integers can grow arbitrarily large. In order to compute the raw two's-complement the way you want it, you would need to specify the desired bit width. Your example shows -199703103 in 64-bit two's complement, but it just as well could have been 32-bit or 128-bit, resulting in a different number of 0xf's at the start.

hex() doesn't do that. I suggest the following as an alternative:

def tohex(val, nbits):   return hex((val + (1 << nbits)) % (1 << nbits))  print tohex(-199703103, 64) print tohex(199703103, 64) 

This prints out:

0xfffffffff418c5c1L 0xbe73a3fL 
like image 193
NPE Avatar answered Oct 21 '22 01:10

NPE