OurFamily Page
OurFamily Page

Reputation: 233

Convert each character in string to ASCII

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.

Upvotes: 3

Views: 35804

Answers (4)

Carl
Carl

Reputation: 44448

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.

#include <string>
#include <iostream>
#include <functional>

int main() {
  const std::string str = "abcde";
  std::cout << std::hash<std::string>()(str) << std::endl;
  return 0;
}

Finally, you can still sum the elements of a string without C++11, using std::accumulate:

#include <string>
#include <iostream>
#include <numeric>

int main() {
  //0x61+0x62+0x63+0x64+0x65=0x1ef=495
  const std::string str = "abcde";
  std::cout << std::accumulate(str.begin(),str.end(),0) << std::endl;
  return 0;
}

Upvotes: 3

EricFromChina
EricFromChina

Reputation: 113

Convert it to an int: int(word[x])

Upvotes: -1

J.N.
J.N.

Reputation: 8421

Supposing you mean std::string or char*, you can sum the characters directly, they are in ASCII representation already (as opposed to Char 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.

Upvotes: 0

perreal
perreal

Reputation: 97948

Each character in a string is already ascii:

#include <string>
int main() {
  int sum = 0;
  std::string str = "aaabbb";
  for (unsigned int i = 0; i < str.size(); i++) {
    sum += str[i];
  }
  return 0;
}

Upvotes: 11

Related Questions