ascii binary string into an integer

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • sathyashrayan

    #1

    ascii binary string into an integer

    Group,
    I have some doubts in the following program.

    ------------------program---------------------
    /*
    ** Make an ascii binary string into an integer.
    */

    #include <string.h>
    unsigned int bstr_i(char *cptr)
    {
    unsigned int i, j = 0;
    while (cptr && *cptr && strchr("01", *cptr))
    {
    i = *cptr++ - '0';
    j <<= 1;
    j |= (i & 0x01);
    }
    return(j);
    }
    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char *argv[])
    {
    char *arg;
    unsigned int x;
    while (--argc)
    {
    x = bstr_i(arg = *++argv);
    printf("Binary %s = %d = %04Xh\n", arg, x, x);
    }
    return EXIT_SUCCESS;
    }
    -----------------------------------------------------------

    My doubts are:
    1)In the expression
    i = *cptr++ - '0';
    the pointer cptr is dereffered and subtracted with the char constant
    '0'. As far as I know, the above expression will return the number of chars
    in-between cptr and '0'. Then the variable i will either 1 or 0.
    Am I correct or wrong?

    2)What is the meaning of "Make an ASCII binary string into an integer."
    Any web reference or a link for the above.

    3)What ever number I input I get the answer 0000h except when I input 1
    by that I will get 0001h. Why is that?

    In short I am very much confused by the above program. Can any one take
    some time in explaining the while block in the function bstr_i().


    --
    "combinatio n is the heart of chess"

    A.Alekhine

    Mail to:
    sathyashrayan AT gmail DOT com






  • Walter Roberson

    #2
    Re: ascii binary string into an integer

    In article <425cd8c5$0$886 $892e7fe2@authe n.white.readfre enews.net>,
    sathyashrayan <sathyashrayan@ REMOVETHISgmail .com> wrote:[color=blue]
    >My doubts are:
    > 1)In the expression
    > i = *cptr++ - '0';
    > the pointer cptr is dereffered and subtracted with the char constant
    >'0'. As far as I know, the above expression will return the number of chars
    >in-between cptr and '0'. Then the variable i will either 1 or 0.
    >Am I correct or wrong?[/color]

    Incorrect.

    Derefferencing a char* gets you a char, so you are doing the
    difference between a char and a different char. If the first
    char falls in the range '0' through '9' then the subtraction
    yields the decimal value that is represented for printing purposes
    by the char (e.g., value 2 if the char is '2'.)
    [color=blue]
    >3)What ever number I input I get the answer 0000h except when I input 1
    > by that I will get 0001h. Why is that?[/color]

    Try entering something like 101 and seeing what the answer is.
    If you experiment with that and 1000 and 11111111 then you
    will likely quickly discovere the answer to your second
    question.
    --
    Look out, there are llamas!

    Comment

    • Jason Curl

      #3
      Re: ascii binary string into an integer

      sathyashrayan wrote:[color=blue]
      > Group,
      > I have some doubts in the following program.
      >
      > ------------------program---------------------
      > /*
      > ** Make an ascii binary string into an integer.
      > */
      >
      > #include <string.h>
      > unsigned int bstr_i(char *cptr)
      > {
      > unsigned int i, j = 0;
      > while (cptr && *cptr && strchr("01", *cptr))
      > {
      > i = *cptr++ - '0';
      > j <<= 1;
      > j |= (i & 0x01);
      > }
      > return(j);
      > }
      > #include <stdio.h>
      > #include <stdlib.h>
      > int main(int argc, char *argv[])
      > {
      > char *arg;
      > unsigned int x;
      > while (--argc)
      > {
      > x = bstr_i(arg = *++argv);
      > printf("Binary %s = %d = %04Xh\n", arg, x, x);
      > }
      > return EXIT_SUCCESS;
      > }
      > -----------------------------------------------------------
      >
      > My doubts are:
      > 1)In the expression
      > i = *cptr++ - '0';
      > the pointer cptr is dereffered and subtracted with the char constant
      > '0'. As far as I know, the above expression will return the number of chars
      > in-between cptr and '0'. Then the variable i will either 1 or 0.
      > Am I correct or wrong?[/color]

      You're correct. *cptr is either '0' or '1' (value 48 or 49) and the
      constant '0' (which is 48) is then subtracted giving either 0 or 1.

      The value of cptr is also incremented to point to the next 'char' in memory.
      [color=blue]
      >
      > 2)What is the meaning of "Make an ASCII binary string into an integer."
      > Any web reference or a link for the above.[/color]

      Think about (1).

      Hint, understand the meaning of a string. It's a sequence of data,
      terminated by a special character.

      In the context of C, it's a sequence of bytes that are in the range
      defined by the ASCII standard, terminated by NUL.
      [color=blue]
      >
      > 3)What ever number I input I get the answer 0000h except when I input 1
      > by that I will get 0001h. Why is that?[/color]

      Again, think about (1). Make sure you understand precisely what the
      input is (and it's a string) and what the output is.

      What's a binary number? This is the basis for computers at a transistor
      level.

      What does 10 give? I would imagine it returns 0002h.
      [color=blue]
      >
      > In short I am very much confused by the above program. Can any one take
      > some time in explaining the while block in the function bstr_i().[/color]

      Sorry if I asked more questions than you did, but this should give you a
      good starting point in researching the meaning of the program.
      [color=blue]
      >
      >
      > --
      > "combinatio n is the heart of chess"
      >
      > A.Alekhine
      >
      > Mail to:
      > sathyashrayan AT gmail DOT com
      >
      >[/color]

      Comment

      • Barry Schwarz

        #4
        Re: ascii binary string into an integer

        On Wed, 13 Apr 2005 14:01:18 +0530, "sathyashra yan"
        <sathyashrayan@ REMOVETHISgmail .com> wrote:
        [color=blue]
        >Group,
        > I have some doubts in the following program.
        >
        >------------------program---------------------
        >/*
        >** Make an ascii binary string into an integer.
        >*/
        >
        >#include <string.h>
        >unsigned int bstr_i(char *cptr)
        >{
        > unsigned int i, j = 0;
        > while (cptr && *cptr && strchr("01", *cptr))[/color]

        The first expression confirms that cptr is not NULL. This is
        "necessary" so that the next expression does not invoke undefined
        behavior.

        The second expression confirms that *cptr is not the '\0' that
        terminates the string (cptr is not past the last valid character in
        the string). This is necessary because if *cptr is '\0' then strchr
        will never return NULL.

        The third expression confirms that *cptr is either a 0 or 1. If *cptr
        is not '0' or '1', strchr will return NULL.

        The loop repeats until one of the three expressions evaluates to NULL
        or '\0', which will be treated as false.
        [color=blue]
        > {[/color]

        At this point, you know that *cptr must be '0' or '1'.
        [color=blue]
        > i = *cptr++ - '0';[/color]

        Consequently, i must be 0 or 1.
        [color=blue]
        > j <<= 1;
        > j |= (i & 0x01);[/color]

        Since i must be 0 or 1, anding it with 0x01 cannot change it. j |= i
        or j += i is just as effective and easier on the eyes.

        In many cases, to be consistent with bases that are not powers of two,
        these two statements are written as
        j = j*BASE + i;
        where BASE is 2 in this case.
        [color=blue]
        > }
        > return(j);
        >}
        >#include <stdio.h>
        >#include <stdlib.h>
        >int main(int argc, char *argv[])
        >{
        > char *arg;
        > unsigned int x;
        > while (--argc)[/color]

        Can argc ever be 0? Probably not on any system this code is likely to
        run on.
        [color=blue]
        > {
        > x = bstr_i(arg = *++argv);
        > printf("Binary %s = %d = %04Xh\n", arg, x, x);[/color]

        %d expects an int. x is an unsigned int. Better to use %u.
        [color=blue]
        > }
        > return EXIT_SUCCESS;
        >}
        >-----------------------------------------------------------
        >
        >My doubts are:[/color]

        snip
        [color=blue]
        >2)What is the meaning of "Make an ASCII binary string into an integer."
        > Any web reference or a link for the above.[/color]

        Whatever the inventor of the exercise wanted it to mean. You seem to
        have interpreted it the same way I did.
        [color=blue]
        >
        >3)What ever number I input I get the answer 0000h except when I input 1
        > by that I will get 0001h. Why is that?[/color]

        I ran your code and got the expected results. Are your values such
        that the last four hex digits are always 0?
        [color=blue]
        >
        >In short I am very much confused by the above program. Can any one take
        >some time in explaining the while block in the function bstr_i().[/color]

        See above



        <<Remove the del for email>>

        Comment

        • sathyashrayan

          #5
          Re: ascii binary string into an integer

          The code is not mine. I took it from C snippet archives. I searches
          for the word "ascii binary string into an integer" in google. I have so
          far got this bellow given code from the snippet archive itself.


          [color=blue][color=green]
          > >Group,
          > > I have some doubts in the following program.
          > >
          > >------------------program---------------------
          > >/*
          > >** Make an ascii binary string into an integer.
          > >*/
          > >
          > >#include <string.h>
          > >unsigned int bstr_i(char *cptr)
          > >{
          > > unsigned int i, j = 0;
          > > while (cptr && *cptr && strchr("01", *cptr))[/color]
          >
          > The first expression confirms that cptr is not NULL. This is
          > "necessary" so that the next expression does not invoke undefined
          > behavior.
          >
          > The second expression confirms that *cptr is not the '\0' that
          > terminates the string (cptr is not past the last valid character in
          > the string). This is necessary because if *cptr is '\0' then strchr
          > will never return NULL.
          >
          > The third expression confirms that *cptr is either a 0 or 1. If *cptr
          > is not '0' or '1', strchr will return NULL.
          >
          > The loop repeats until one of the three expressions evaluates to NULL
          > or '\0', which will be treated as false.
          >[color=green]
          > > {[/color]
          >
          > At this point, you know that *cptr must be '0' or '1'.
          >[color=green]
          > > i = *cptr++ - '0';[/color]
          >
          > Consequently, i must be 0 or 1.
          >[color=green]
          > > j <<= 1;
          > > j |= (i & 0x01);[/color]
          >
          > Since i must be 0 or 1, anding it with 0x01 cannot change it. j |= i
          > or j += i is just as effective and easier on the eyes.[/color]

          The point of my confussion. I got clared with your explanation. The variouble
          i is either 0 or 1 according the while loop. So ANDin the i with 0x01 is useless.
          Is that what you wanted to say.Correct? (Sorry.I lack in understanding the high
          level discussions)

          [color=blue]
          > In many cases, to be consistent with bases that are not powers of two,
          > these two statements are written as
          > j = j*BASE + i;
          > where BASE is 2 in this case.
          >[color=green]
          > > }
          > > return(j);
          > >}
          > >#include <stdio.h>
          > >#include <stdlib.h>
          > >int main(int argc, char *argv[])
          > >{
          > > char *arg;
          > > unsigned int x;
          > > while (--argc)[/color]
          >
          > Can argc ever be 0? Probably not on any system this code is likely to
          > run on.
          >[color=green]
          > > {
          > > x = bstr_i(arg = *++argv);
          > > printf("Binary %s = %d = %04Xh\n", arg, x, x);[/color]
          >
          > %d expects an int. x is an unsigned int. Better to use %u.
          >[color=green]
          > > }
          > > return EXIT_SUCCESS;
          > >}
          > >-----------------------------------------------------------
          > >
          > >My doubts are:[/color]
          >
          > snip
          >[color=green]
          > >2)What is the meaning of "Make an ASCII binary string into an integer."
          > > Any web reference or a link for the above.[/color]
          >
          > Whatever the inventor of the exercise wanted it to mean. You seem to
          > have interpreted it the same way I did.
          >[color=green]
          > >
          > >3)What ever number I input I get the answer 0000h except when I input 1
          > > by that I will get 0001h. Why is that?[/color]
          >
          > I ran your code and got the expected results. Are your values such
          > that the last four hex digits are always 0?
          >[/color]

          input output
          10 Binary 10 = 1 = 0001h
          100 Binary 100 = 3 = 0003h

          Any other value outputs zero.
          [color=blue][color=green]
          > >
          > >In short I am very much confused by the above program. Can any one take
          > >some time in explaining the while block in the function bstr_i().[/color]
          >
          > See above
          >
          >
          >
          > <<Remove the del for email>>[/color]

          Extra: Answer to my first question:

          Walter Roberson in this replay thread saying that it is wrong. But
          Jason Curl says it is correct. This group will correct who ever gives
          a wrong, irrelevant answer. But it this case there is silence. Why?


          --
          "combinatio n is the heart of chess"

          A.Alekhine

          Mail to:
          sathyashrayan AT gmail DOT com



          Comment

          • Walter Roberson

            #6
            Re: ascii binary string into an integer

            In article <425e3289$0$482 99$892e7fe2@aut hen.white.readf reenews.net>,
            sathyashrayan <sathyashrayan@ REMOVETHISgmail .com> wrote:
            [color=blue]
            >Extra: Answer to my first question:[/color]
            [color=blue]
            > Walter Roberson in this replay thread saying that it is wrong. But
            >Jason Curl says it is correct. This group will correct who ever gives
            >a wrong, irrelevant answer. But it this case there is silence. Why?[/color]

            Your explanation was not right.

            You said that a pointer was dereferenced and '0' was subtracted.
            The way you phrased it implied that '0' was subtracted from the
            pointer, rather than from the value at the location pointed to.
            '0' is an integer (with value 48), so subtracting '0' from
            a char pointer would give the location 48 characters before,
            which in this case is not even likely to be in the same object.

            You continued on to say that the subtraction gave the number
            of characters between cptr and '0'. '0' is a character (that is,
            an integer), not a pointer, so the number of characters between
            cptr and '0' is not defined. And it's not what the code does anyhow:
            the code gives the numeric difference between what cptr *points to*
            and the integer value represented by '0', not between cptr *itself*
            and something.

            The "number of characters" between two characters would imply to
            me that the order of the two characters was not relevant for
            the comparison -- e.g., I would say that the number of
            characters "between" 'A' and 'E' is the same as the number of
            characters "between" 'E' and 'A'. That's not the value that
            subtraction of characters gives you, though: 'E' - 'A' is
            positive and easily defined, but 'A' - 'E' is logically negative
            and I would have to look up the rules for subtraction when
            unsigned quantities are involved. Thus, I would not normally phrase
            a character subtraction as the number of characters between the two.


            It wasn't the code that was incorrect, it was the way you explained
            it. Some of what you said could possibly be explained as a language
            difference, but when you are working with C, there are big differences
            between cptr and *cptr, so you need to be careful to add in the right
            operators.

            --
            Oh, to be a Blobel!

            Comment

            Working...