12,401,173 members (61,446 online)
Rate this:
See more:
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 16-Nov-11 11:33am
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).
SAKryukov 16-Nov-11 18:31pm

Right. I would accept it as a solution.
--SA

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.

Top Experts
Last 24hrsThis month
 OriginalGriff 320 ppolymorphe 165 Richard Deeming 150 Vincent Maverick Durano 140 0x01AA 125
 OriginalGriff 6,963 ppolymorphe 2,950 Karthik Bangalore 2,737 F-ES Sitecore 2,082 Richard MacCutchan 2,077

Web02 | 2.8.160721.1 | Last Updated 16 Nov 2011