Click here to Skip to main content
13,048,584 members (79,170 online)
Rate this:
Please Sign up or sign in to vote.
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.

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.
gladiatron 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170713.1 | Last Updated 16 Nov 2011
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100