开发者

How to convert hex string to hex number?

I have integer number in ex. 16 and i am trying to convert this number to a hex number. I tried to achieve this by using hex function but whenever you provide a integer number to the hex function it returns string representation of hex number,

my_number = 16
hex_no = hex(my_number)    
print type(hex_no) // It will print type of hex_no as str.

Can someone please tell me how to convert hex numbe开发者_高级运维r in string format to simply a hex number.

Thanks!!


>>> print int('0x10', 16)
16


Sample Code :

print "%x"%int("2a",16)


Are you asking how to convert the string format hexadecimal value '16' into an integer (that is, end up with an integer with decimal value 22)? It's not clear from your question. If so, you probably want int('16', 16)


Using the string formatters (new first, then old):

>>> '{:x}'.format( 12345678 )
'bc614e'

>>> '%x' % ( 12345678 )
'bc614e'


Your code works for me, no apostrophes added.

Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> my_number = 16
>>> hex_no = hex(my_number)
>>> print hex_no
0x10
>>> _

Note, by the way, that there's no such thing as a "hex number". Hex is just a way to specify a number value. In the computer's memory that number value is usually represented in binary, no matter how it's specified in your source code (decimal, hex, whatever).

Cheers & hth.,

– Alf


I think here most of the answers were misinterpreted or they understood the question wrongly.

To answer to your question it is IMPOSSIBLE to convert resultant string representation of Hex data to Hex numbers(integer representation).

Because, when you convert an integer to hex by doing following

>>> a = hex(34)
>>> print type(a)
<type 'str'>
>>> print a
0x22
>>> a
'0x22'

And some answers were confused here,

>>> print a
0x22
>>> a
'0x22'

When you type print a in interpreter it will result the string data WITHOUT quotes and If you simply type the variable name without using print statement then it would print the string data WITH single/double quotes.

Though the resultant value is Hex data but the representation is in STRING.

As per Python docs you cannot convert to Hex number as I told earlier.

Thanks.


With Python 2.6.5 on MS Windows Vista, the command line interpreter behaves this way:

>>>hex(16)
'0x10'
>>>print hex(16)
0x10

I guess this is the normal behavior:

>>>'abc'
'abc'
>>>print 'abc'
abc

I hope it helps


def add_hex2(hex1, hex2):
    """add two hexadecimal string values and return as such"""
    return hex(int(hex1, 16) + int(hex2, 16))
print add_hex2('0xff', '0xff')  # 0x1fe
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜