Click here to Skip to main content
Rate this: bad
good
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.
 
Cheers
Posted 16-Nov-11 12:33pm
Comments
TRK3 at 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 at 16-Nov-11 18:31pm
   
Right. I would accept it as a solution.
--SA
gladiatron at 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
0 OriginalGriff 350
1 Jochen Arndt 190
2 Richard MacCutchan 135
3 Sergey Alexandrovich Kryukov 120
4 DamithSL 95
0 OriginalGriff 6,045
1 DamithSL 4,611
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,310


Advertise | Privacy | Mobile
Web02 | 2.8.141220.1 | Last Updated 16 Nov 2011
Copyright © CodeProject, 1999-2014
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