We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,586 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Hexadecimal to Decimal (Python)

1
By vegaseat on Oct 12th, 2005 11:19 am

This snippet explores the change of a hexadecimal (base 16) string to a denary (base 10) integer and the reverse. Interestingly Python allows the representation of the hexadecimal string in two different forms. For instance 255 can be changed to 'FF' (also 'ff') or '0xff'. Any of these hexadecimal strings return the correct value of 255 again.

# change a hexadecimal string to decimal number and reverse
# check two different representations of the hexadecimal string
# negative values and zero are accepted
# tested with Python24        vegaseat     11oct2005

def dec2hex(n):
    """return the hexadecimal string representation of integer n"""
    return "%X" % n

def hex2dec(s):
    """return the integer value of a hexadecimal string s"""
    return int(s, 16)

print "dec2hex(255)  =", dec2hex(255)    # FF
print "hex2dec('FF') =", hex2dec('FF')   # 255

print

print "hex(255) =", hex(255)                # 0xff
print "hex2dec('0xff') =", hex2dec('0xff')  # 255
a=input("enter number in decimal :")

def cal(a):
    if a<10:
        b=str(a)
    elif a==10:
        b="A"
    elif a==11:
        b="B"
    elif a==12:
        b="C"
    elif a==13:
        b="D"
    elif a==14:
        b="E"
    else:
        b="F"
    return b
b=a
L1=""
while True:
    c=b%16
    if b<16:
        L1=L1+cal(c)
        break
    else:
        L1=L1+cal(c)
    b=b/16
c=""
for i in reversed(L1):
    c=c+i
print c
warunn
Newbie Poster
2 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page generated in 0.0563 seconds using 2.66MB