Is this an acceptable use of "ASCII arithmetic"?
Posted
by jmgant
on Stack Overflow
See other posts from Stack Overflow
or by jmgant
Published on 2010-03-23T20:15:29Z
Indexed on
2010/03/23
20:23 UTC
Read the original article
Hit count: 223
c++
I've got a string value of the form 10123X123456
where 10
is the year, 123
is the day number within the year, and the rest is unique system-generated stuff. Under certain circumstances, I need to add 400 to the day number, so that the number above, for example, would become 10523X123456
.
My first idea was to substring those three characters, convert them to an integer, add 400 to it, convert them back to a string and then call replace
on the original string. That works.
But then it occurred to me that the only character I actually need to change is the third one, and that the original value would always be 0-3, so there would never be any "carrying" problems. It further occurred to me that the ASCII code points for the numbers are consecutive, so adding the number 4 to the character "0", for example, would result in "4", and so forth. So that's what I ended up doing.
My question is, is there any reason that won't always work? I generally avoid "ASCII arithmetic" on the grounds that it's not cross-platform or internationalization friendly. But it seems reasonable to assume that the code points for numbers will always be sequential, i.e., "4" will always be 1 more than "3". Anybody see any problem with this reasoning?
Here's the code.
string input = "10123X123456";
input[2] += 4;
//Output should be 10523X123456
© Stack Overflow or respective owner