Stuck again, still, im learning from my large list of mistakes, haha
so this time im trying to convert a decimal to hexadecimal, i tried using hex(number)
but its not suitable for the situation as this returns a string. and i dont know how or if i can convert a string to hexadecimal. I tried to use string formatting as follows;
return "%x" % num

the objective is as follows
"""
Format string output by using the '%' operator

Examples

>>> 1.0/3
0.33333333333333331
>>> print "%.2f" % (1.0/3) # Convert to floating point with 2 decimal place
0.33
>>> name = "John"
>>> age = 27
>>> print "My name is %s. I am %d years old." % (name, age)
My name is John. I am 27 years old.
>>> dec2hex(11)
'0x0b'

"""

dec2hex(34) should result with the following output;
0x22
and dec2hex(10) should result with;
0x0a

You could add '0x' to format string explicitly. Alternately you can print result of hex-function.

Answered by vegaseat 1,735 in a post from

Example ...

# two ways to represent integer 1234 as a hexadecimal number
# 0x is the official prefix for a hexnumber
# the results appear different, but both are of type string
# and change back to base 10 properly
# tested with Python27

n = …

All 9 Replies

i tried, it didn't give the desired result.

You could add '0x' to format string explicitly. Alternately you can print result of hex-function.

Example ...

# two ways to represent integer 1234 as a hexadecimal number
# 0x is the official prefix for a hexnumber
# the results appear different, but both are of type string
# and change back to base 10 properly
# tested with Python27

n = 1234

# using the hex() function gives 0x prefix
hex1 = hex(n)
print(hex1, type(hex1), int(hex1,16))

# using the format operator % does not give 0x prefix
# Python's int() function accepts this form too
hex2 = "%x" % n
print(hex2, type(hex2), int(hex2,16))

# using the format operator % add the 0x prefix
hex3 = "0x%x" % n
print(hex3, type(hex3), int(hex3,16))

''' my output >>
('0x4d2', <type 'str'>, 1234)
('4d2', <type 'str'>, 1234)
('0x4d2', <type 'str'>, 1234)
'''

You must use zero paded fixed length format.

You must use zero paded fixed length format.

sorry, i dont understand what you mean.
could you post the answer for me to look at and try and comprehend?

# Write a function that does a decimal to hexadecimal conversion.
# Hint: Make use of "%x" for hexadecimal format.
def dec2hex(num):
return str('0x' + '%.2x' % num)

Doing python tutorial, some of the examples are badly written, hard to understand what they want. the str() might be unnecessary, .2x gives you two digits to the right of the x

I feel ya brotha

# Write a function that does a decimal to hexadecimal conversion.
# Hint: Make use of "%x" for hexadecimal format.
def dec2hex(num):
return str('0x' + '%.2x' % num)

Doing python tutorial, some of the examples are badly written, hard to understand what they want. the str() might be unnecessary, .2x gives you two digits to the right of the x

I feel ya brotha