tags:

views:

155

answers:

6

Hello all,
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 number in string format to simply a hex number.
Thanks in advance
Rupesh Chavan

+2  A: 

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

Alf P. Steinbach
+1. `print` doesn't add quotes. Perhaps the OP is typing `hex_no` and hitting `enter`?
Manoj Govindan
Nice Catch Alf. Thanks..
Rupesh Chavan
+2  A: 

Sample Code :

print "%x"%int("2a",16)
Emil
+5  A: 
>>> print int('0x10', 16)
16
Ignacio Vazquez-Abrams
+2  A: 

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)

Paul
+1. Question is not clear. But this is a good answer if the OP is trying to read an integer from the hex string.
Manoj Govindan
I want to get a hexadecimal value out of string formatted hexadecimal. ex. '0x16' i want it as 0x16
Rupesh Chavan
`0x16` *doesn't exist* in a running program! It is either `'0x16'` or `22` (= `int('0x16', 16)`).
Tim Pietzcker
A: 

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

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

>>> '%x' % ( 12345678 )
'bc614e'
poke
A: 

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

luc