binary input

I have a binary string for input, for example 0110011, the input is being read left to right one at a time; in the ASCII chart decimal 48 is ASCII 0, and 49 is ASCII 1; how would putting each character of the input through this snippet of code as it is being read affect the input: (i=ch -'0') in words i equals char minus zero getchar is getting the input.
yes, you can get the value of the digit by peeling it off the ascii table as you said.
or you can just do something like

forceinline char/bool getbindigit(char c)
{
if (c == '1')
return 1; ///or true
return 0; // or false
}

or :? statement to do the same, some say its faster.


note that its not a string after you do this. ascii 0 is end of string, and I don't even know what it does if you print a string with one in the middle of it, with a char array it just stops right there. 1 isn't anything friendly to print either, its some control character. At this point all its good for is turning the binary back into an integer value.

when I was doing embedded C we had a guy with a giant include file of # defines
Ob01100
etc (letter O not zero) that he used and added to when he had a new value. It was horrible, but it worked back then.

Last edited on
thank you for responding!! so if the input is a string of 0's 1's the compiler reads 48 decimal for each 0 and 49 for 1 therefore I have to tell it that I want
it to interpret my 0 and 1 as 0 and 1 and not something else.
> in the ASCII chart decimal 48 is ASCII 0, and 49 is ASCII 1

The encoding of the characters in the execution character set is locale specific; it need not (and sometimes does not) correspond to the encoding as specified by ASCII.

However, C++ does guarantee that, no matter what character encoding is in use:
In both the source and execution basic character sets, the value of each character after 0 in the list of decimal digits shall be one greater than the value of the previous. - IS

ie. if the value of '0' is 147, then the value of '1' would be 148, the value of '2' would be 149 and so on.

Therefore, if the character ch is a character representing a decimal digit (std::isdigit(ch) is true),
then ch - '0' would give that digit as an integer. '7' - '0' == 7 etc.
Topic archived. No new replies allowed.