Steve
Steve

Reputation: 363

Convert from Ascii to hex, then sum result of the numbers

We have to write a function that takes a string and returns a number.

Every character of the string should be converted to the hex value of its ascii code first. The result should be the sum of the numbers in the hex strings (ignore letters).

We are struggling with converting ascii to hex..

This is what we have so far

def hex_hash(code):
# ascii to hex
# remove all the letters
# return the sum of the numbers 

#code.encode('hex')
#code.hex()

#code = hex(code)

code = code.fromascii(code).encode('hex')

sum = 0

for i in code:
    if i.isdigit():
        sum = sum + i 
return sum

Upvotes: 0

Views: 920

Answers (2)

atmostmediocre
atmostmediocre

Reputation: 198

def func(s):
    sm = 0
    for i in s:
        a = hex(ord(i))
        for j in a:
            if j.isdigit():
                sm += int(j)
    return sm

Sample input:

>>> func("Hello, World!")
91

EDIT: Explanation of the hex(ord(i)) part

ord(x) gives the ASCII value of that character, for example:

>>> ord('A')
65
>>> ord('0')
48

hex(x) returns hexadecimal string representation of an integer:

>>> hex(32)
'0x20'
>>> hex(100)
'0x64'
>>> hex(10)
'0xa'

Upvotes: 0

bla
bla

Reputation: 1870

def hex_hash(s):
    h = ''.join(str(hex(ord(x))) for x in s)
    return sum(int(x) for x in h if x.isdigit())

sample usage:

>>> def hex_hash(s):
...     h = ''.join(str(hex(ord(x))) for x in s)
...     return sum(int(x) for x in h if x.isdigit())
... 
>>> 
>>> hex_hash('Yo')
20
>>> hex_hash("Hello, World!")
91

Upvotes: 1

Related Questions