# How should a string be converted to a number for use by a hash function? [closed]

After reading this question/answer I thought I'd try and implement the SHA-256 for my own education. My initial thought for converting the input into a number was to use a line of code like sum([ord(character) for character in input_string]), I quickly realized this is a terrible idea because I'm greatly reducing the entropy of the input by mapping a lot of highly varied strings to a relatively small number of integers. My second though was to get a hex representation of the string then get the base 16 integer representation of that hex string

import binascii
input_integer = int(binascii.hexlify('hello world'), 16)


However since I'm not an expert in hashing algorithms there may be something wrong with my second implementation that I'm not aware of.

How do you convert a string to a number to be used in a hash algorithm?

My code is written in python, for reference

• You could use Python's built in int() function. Pass your string and its base: int('0100',2)=4. Default is big endian. – Q-Club Apr 11 '17 at 20:03
• I'm asking if my second example is secure. I don't need help with the implementation ... yet. – John Apr 11 '17 at 20:06
• I have absolutely no idea what you are trying to do. You say you are trying to "implement the (sic) SHA-256", but your algorithm obviously has nothing to do with SHA-256. – fkraiem Apr 11 '17 at 20:12
• @fkraiem SHA-256 operates on number not strings. How do you safely convert a number to a string so that you can perform the hashing operations on the number? – John Apr 11 '17 at 20:16
• I meant string to number. – John Apr 11 '17 at 20:42

• I'm not asking about the input format. If you convert your string into ASCII bytes, for example, you'll end up with a set of 8 bit numbers. Join them together and there's your input. this is the answer I was looking for. Your explanation of how sha256 works doesn't account for cases where the input exceeds 448 bits. I already know that you pad to the (nearest multiple of 512) - 64. Thanks for answering. – John Apr 11 '17 at 20:35