Could anyone tell me how to easily convert each character in a string to ASCII value so that I can sum the values? I need to sum the values for a hash function.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- how to split a list into a given number of sub-lis
- thread_local variables initialization
相关文章
- JSP String formatting Truncate
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
Convert it to an int: int(word[x])
Supposing you mean
std::string
orchar*
, you can sum the characters directly, they are in ASCII representation already (as opposed toChar
in Java or .net). Be sure to use a big enough result type (int
at least).On the other hand, there should be plenty of hash functions for strings in C++ out there, unless this is an excercise, you'd better choose one of those.
Each character in a string is already ascii:
To create a hash, you basically only need the integer value of each character in the string and not the ASCII value. They are two very different things. ASCII is an encoding. Your string could be UTF-8 encoded too, which will still mean your string ends with a single NULL, but that each character could take up more than 1 byte. Either way, perreal's solution is the one you want. However, I wrote this as a separate answer, because you do need to understand the difference between an encoding and a storage type, which a char is.
It is also probably worth mentioning that with C+11, there is a hash function that is built into the standard library. This is how you would use it.
Finally, you can still sum the elements of a string without C++11, using std::accumulate: