Click here to Skip to main content
15,887,888 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi folks,

I have a potentially silly sounding question considering the fact that there are several conventional ways of doing it, but I was wondering if anyone knows of a fast way of computing the ASCII value of a whole string of characters. Possibly using some sort of bit-filddling hacks. The conventional or my approach is to convert the string to a char array and then type cast every element to int and add every value obtained to compute the total ASCII value of the string.

Apparently, its an O(n) way of doing it becoz of the loop that has to iterate over the length of the array. Is there a way to reduce this computation time? Appreciate any help guys.

Cheers
Posted
Comments
TRK3 16-Nov-11 17:56pm    
"ASCII value of a string" is kind of an odd concept.

But, if you define "ASCII value of a string" as "the sum of the ASCII values of each character in the string", then what you are asking is:

"Is there a faster way to add up N numbers than looping over the N numbers and adding them up?"

It is by definition an O(N) problem. There isn't a faster way, except to optimize the casting / conversion / etc.

If you do it in C/C++ or assembler, then the "convert to char array and type cast" steps are zero cost and you are left simply with add and loop, but it's still O(N).
Sergey Alexandrovich Kryukov 16-Nov-11 18:31pm    
Right. I would accept it as a solution.
--SA
I.explore.code 16-Nov-11 18:43pm    
I agree with you, I just did some really heavy load testing with loads of massive strings to stress out the computation function, the computation time hardly crossed a 8-10 seconds and that too when all those strings are being read from a text file. So I would concur that O(n) is not really too bad. I also tried in C# using loops and also lambda expressions, surprisingly lambdas were slower than for loop but the computation time was always constant. Oh and yes, by ASCII value of string i do mean sum of ASCIIs of all the individual characters. :) Thanks a lot mate.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900