How to print an array of char backward.

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

    How to print an array of char backward.

    I have this code here, it converts decimal numbers to binary. There is
    one problem. The output is printed 'in reverse' and I have no clue at all
    how to solve this problem.

    Output of program:

    Decimal number: 10
    Binary representation: 0101
    (It should be 1010, and not 0101...)

    I would be glad if someone could help me. Maybe there is some function,
    which does the trick... (I have no idea.)

    Thanks.

    /*************** *************** *************** *************** **********/
    #include <stdio.h>
    #include <string.h>

    int main()
    {
    char bin[25] = "";
    int dec;

    printf("Decimal number: ");
    scanf("%d", &dec);

    do {
    if (dec % 2 == 0)
    strcat(bin, "0");
    else {
    strcat(bin, "1");
    dec--;
    }
    dec = dec / 2;
    } while (dec 0);
    printf("Binary representation: %s\n", bin);

    return 0;
    }
    /*************** *************** *************** *************** **********/
  • santosh

    #2
    Re: How to print an array of char backward.

    hank wrote:
    I have this code here, it converts decimal numbers to binary. There is
    one problem. The output is printed 'in reverse' and I have no clue at
    all how to solve this problem.
    >
    Output of program:
    >
    Decimal number: 10
    Binary representation: 0101
    (It should be 1010, and not 0101...)
    >
    I would be glad if someone could help me. Maybe there is some
    function, which does the trick... (I have no idea.)
    You could reverse the string in place before printing it. There is no
    standard string reverse function, but it's easy enough to write one. As
    an alternative you could just iterate backwards through the string
    while printing it, character by character.

    <snip>

    Comment

    • sohijb.edrisy@gmail.com

      #3
      Re: How to print an array of char backward.

      You could reverse the string in place before printing it. There is no
      standard string reverse function, but it's easy enough to write one. As
      an alternative you could just iterate backwards through the string
      while printing it, character by character.
      >
      <snip>
      Here's what I should do.

      (Put this after the do-while{} loop)

      ////////////////////////////////////////////////////////////////////////
      length = strlen(bin);
      int i;

      for (i = length - 1; i >= 0; i--)
      {
      printf("%c", bin[i]);
      }
      ///////////////////////////////////////////////////////////////////////

      Comment

      • Andrew Kerr

        #4
        Re: How to print an array of char backward.

        santosh wrote:
        hank wrote:
        >
        >I have this code here, it converts decimal numbers to binary. There is
        >one problem. The output is printed 'in reverse' and I have no clue at
        >all how to solve this problem.
        >
        You could reverse the string in place before printing it.
        Or you could write it correctly.

        /*************** *************** *************** *************** **********/
        #include <stdio.h>
        #include <string.h>

        void fprint_binary_r epresentation(F ILE *out, unsigned char byte) {
        char str_rep[9] = {0};
        int i;
        for (i = 7; i >= 0; i--) {
        str_rep[7 - i] = ((byte & (1 << i)) ? '1' : '0');
        }
        fprintf(out, "%s", str_rep);
        }

        int main() {
        fprint_binary_r epresentation(s tdout, 10); // prints 00001010

        return 0;
        }

        /*************** *************** *************** *************** **********/

        Comment

        • Lew Pitcher

          #5
          Re: How to print an array of char backward.

          In comp.lang.c, sohijb.edrisy@g mail.com wrote:
          >You could reverse the string in place before printing it. There is no
          >standard string reverse function, but it's easy enough to write one. As
          >an alternative you could just iterate backwards through the string
          >while printing it, character by character.
          >>
          ><snip>
          >
          Here's what I should do.
          >
          (Put this after the do-while{} loop)
          >
          ////////////////////////////////////////////////////////////////////////
          length = strlen(bin);
          int i;
          >
          for (i = length - 1; i >= 0; i--)
          {
          printf("%c", bin[i]);
          }
          ///////////////////////////////////////////////////////////////////////
          How about...

          void RevPrint(char *string)
          {
          if (*string)
          {
          RevPrint(string +1);
          printf("%c",*st ring);
          }
          }

          used as...
          printf("Binary representation: "); RevPrint(bin);



          --
          Lew Pitcher

          Master Codewright & JOAT-in-training | Registered Linux User #112576
          http://pitcher.digitalfreehold.ca/ | GPG public key available by request
          ---------- Slackware - Because I know what I'm doing. ------


          Comment

          • =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?=

            #6
            Re: How to print an array of char backward.

            On May 30, 8:34 pm, hank <ilona-radema...@hotma il.comwrote:
              do {
                if (dec % 2 == 0)
                  strcat(bin, "0");
                else {
                  strcat(bin, "1");
                  dec--;
                }
                dec = dec / 2;
              } while (dec 0);

            This algorithm can be written differently depending on whether you do
            or do not want leading zeroes.

            My major criticism of your original code is that it takes a human
            approach rather than a computer approach. A computer approach would be
            to use (x & 1) instead of (x % 2), and also to use shifting instead of
            division by 2.

            If I didn't want leading zeroes, I'd go with something like the
            following:

            (Disclaimer: Untested code thrown together in the last two minutes)

            #define QUANTITY_VALUE_ BITS(int_type) /* fancy macro */

            void GetBinary(unsig ned const val, char *p)
            {
            unsigned mask = 1u << (QUANTITY_VALUE _BITS(unsigned) - 1);

            do if (val & mask) goto We_Have_Ones;
            while (mask >= 1);

            /* If here is reached, there's no 1's */
            p[0] = '0';
            p[1] = 0;
            return; /* <--- And we're gone! */

            We_Have_Ones:

            *p++ = '1';

            while (mask >>= 1) *p++ = (val & mask ? '1' : '0');

            *p = 0;
            }

            Comment

            • pete

              #7
              Re: How to print an array of char backward.

              Tomás Ó hÉilidhe wrote:
              On May 30, 8:34 pm, hank <ilona-radema...@hotma il.comwrote:
              >
              > do {
              > if (dec % 2 == 0)
              > strcat(bin, "0");
              > else {
              > strcat(bin, "1");
              > dec--;
              > }
              > dec = dec / 2;
              > } while (dec 0);
              >
              >
              This algorithm can be written differently depending on whether you do
              or do not want leading zeroes.
              >
              My major criticism of your original code is that it takes a human
              approach rather than a computer approach. A computer approach would be
              to use (x & 1) instead of (x % 2), and also to use shifting instead of
              division by 2.
              I disagree.
              The code as written, is easy to understand.
              If he were doing decimal representation,
              he would be dividing by 10 instead.

              It's entirely possible and likely that a compiler
              will know as much as you do about these simple micro-optimizations
              and generate the same machine code for (x & 1) as it does for (x % 2).

              If the code is shown to be not fast enough,
              then I would investigate the changes that you suggest,
              otherwise legibility is a higher priority.

              --
              pete

              Comment

              • Richard

                #8
                Re: How to print an array of char backward.

                pete <pfiland@mindsp ring.comwrites:
                Tomás Ó hÉilidhe wrote:
                >On May 30, 8:34 pm, hank <ilona-radema...@hotma il.comwrote:
                >>
                >> do {
                >> if (dec % 2 == 0)
                >> strcat(bin, "0");
                >> else {
                >> strcat(bin, "1");
                >> dec--;
                >> }
                >> dec = dec / 2;
                >> } while (dec 0);
                >>
                >>
                >This algorithm can be written differently depending on whether you do
                >or do not want leading zeroes.
                >>
                >My major criticism of your original code is that it takes a human
                >approach rather than a computer approach. A computer approach would be
                >to use (x & 1) instead of (x % 2), and also to use shifting instead of
                >division by 2.
                >
                I disagree.
                The code as written, is easy to understand.
                If he were doing decimal representation,
                he would be dividing by 10 instead.
                >
                It's entirely possible and likely that a compiler
                will know as much as you do about these simple micro-optimizations
                and generate the same machine code for (x & 1) as it does for (x % 2).
                >
                If the code is shown to be not fast enough,
                then I would investigate the changes that you suggest,
                otherwise legibility is a higher priority.
                If the code was being maintained by Bill possibly. But if a C programmer
                does not understand something x&1 or shift right/left then they have no
                business writing in C in a commercial setting.

                Comment

                • Ben Bacarisse

                  #9
                  Re: How to print an array of char backward.

                  Richard<rgrdev@ gmail.comwrites :
                  pete <pfiland@mindsp ring.comwrites:
                  >
                  >Tomás Ó hÉilidhe wrote:
                  <snip>
                  >>My major criticism of your original code is that it takes a human
                  >>approach rather than a computer approach. A computer approach would be
                  >>to use (x & 1) instead of (x % 2), and also to use shifting instead of
                  >>division by 2.
                  >>
                  >I disagree.
                  >The code as written, is easy to understand.
                  >If he were doing decimal representation,
                  >he would be dividing by 10 instead.
                  >>
                  >It's entirely possible and likely that a compiler
                  >will know as much as you do about these simple micro-optimizations
                  >and generate the same machine code for (x & 1) as it does for (x % 2).
                  >>
                  >If the code is shown to be not fast enough,
                  >then I would investigate the changes that you suggest,
                  >otherwise legibility is a higher priority.
                  >
                  If the code was being maintained by Bill possibly. But if a C programmer
                  does not understand something x&1 or shift right/left then they have no
                  business writing in C in a commercial setting.
                  But what of pete's first point? I much prefer % and / in the context
                  because it expresses a general algorithm. Even if asked to do just
                  base 2, might be tempted to write:

                  #define BASE 2
                  #define DIGITS "01"

                  ....

                  while (num) {
                  *--p = DIGITS[num % BASE];
                  num /= BASE;
                  }

                  just because it is so self-documenting and obviously extensible. The
                  shift/mask method is entirely understandable, but it obscures (ever so
                  slightly) the algorithm.

                  --
                  Ben.

                  Comment

                  • CBFalconer

                    #10
                    Re: How to print an array of char backward.

                    sohijb.edrisy@g mail.com wrote:
                    >
                    .... snip ...
                    >
                    /////////////////////////////////////////////////////////////////
                    length = strlen(bin);
                    int i;
                    >
                    for (i = length - 1; i >= 0; i--)
                    {
                    printf("%c", bin[i]);
                    }
                    /////////////////////////////////////////////////////////////////
                    All those silly division symbols create syntax errors on C90. :-)

                    --
                    [mail]: Chuck F (cbfalconer at maineline dot net)
                    [page]: <http://cbfalconer.home .att.net>
                    Try the download section.

                    ** Posted from http://www.teranews.com **

                    Comment

                    • Richard

                      #11
                      Re: How to print an array of char backward.

                      Ben Bacarisse <ben.usenet@bsb .me.ukwrites:
                      Richard<rgrdev@ gmail.comwrites :
                      >
                      >pete <pfiland@mindsp ring.comwrites:
                      >>
                      >>Tomás Ó hÉilidhe wrote:
                      <snip>
                      >>>My major criticism of your original code is that it takes a human
                      >>>approach rather than a computer approach. A computer approach would be
                      >>>to use (x & 1) instead of (x % 2), and also to use shifting instead of
                      >>>division by 2.
                      >>>
                      >>I disagree.
                      >>The code as written, is easy to understand.
                      >>If he were doing decimal representation,
                      >>he would be dividing by 10 instead.
                      >>>
                      >>It's entirely possible and likely that a compiler
                      >>will know as much as you do about these simple micro-optimizations
                      >>and generate the same machine code for (x & 1) as it does for (x % 2).
                      >>>
                      >>If the code is shown to be not fast enough,
                      >>then I would investigate the changes that you suggest,
                      >>otherwise legibility is a higher priority.
                      >>
                      >If the code was being maintained by Bill possibly. But if a C programmer
                      >does not understand something x&1 or shift right/left then they have no
                      >business writing in C in a commercial setting.
                      >
                      But what of pete's first point? I much prefer % and / in the context
                      because it expresses a general algorithm. Even if asked to do just
                      base 2, might be tempted to write:
                      >
                      #define BASE 2
                      #define DIGITS "01"
                      >
                      ...
                      >
                      while (num) {
                      *--p = DIGITS[num % BASE];
                      num /= BASE;
                      }
                      >
                      just because it is so self-documenting and obviously extensible. The
                      shift/mask method is entirely understandable, but it obscures (ever so
                      slightly) the algorithm.
                      I have no problem with his code, but I would suggest that (especially
                      the shift) the bit test and the shift are obvious to any half decent C
                      programmer.

                      Comment

                      • Ben Bacarisse

                        #12
                        Re: How to print an array of char backward.

                        Richard<rgrdev@ gmail.comwrites :
                        Ben Bacarisse <ben.usenet@bsb .me.ukwrites:
                        >
                        >Richard<rgrdev @gmail.comwrite s:
                        >>
                        >>pete <pfiland@mindsp ring.comwrites:
                        <snip>
                        >>>I disagree.
                        >>>The code as written, is easy to understand.
                        >>>If he were doing decimal representation,
                        >>>he would be dividing by 10 instead.
                        <snip other points>
                        >>If the code was being maintained by Bill possibly. But if a C programmer
                        >>does not understand something x&1 or shift right/left then they have no
                        >>business writing in C in a commercial setting.
                        >>
                        >But what of pete's first point? I much prefer % and / in the context
                        >because it expresses a general algorithm.
                        <snip>
                        I have no problem with his code, but I would suggest that (especially
                        the shift) the bit test and the shift are obvious to any half decent C
                        programmer.
                        Right and I agreed. I wondered if you had anything to add about his
                        first point which is not about whether anyone should or should not be
                        able to read the alternative.

                        --
                        Ben.

                        Comment

                        • Richard

                          #13
                          Re: How to print an array of char backward.

                          Ben Bacarisse <ben.usenet@bsb .me.ukwrites:
                          Richard<rgrdev@ gmail.comwrites :
                          >
                          >Ben Bacarisse <ben.usenet@bsb .me.ukwrites:
                          >>
                          >>Richard<rgrde v@gmail.comwrit es:
                          >>>
                          >>>pete <pfiland@mindsp ring.comwrites:
                          <snip>
                          >>>>I disagree.
                          >>>>The code as written, is easy to understand.
                          >>>>If he were doing decimal representation,
                          >>>>he would be dividing by 10 instead.
                          <snip other points>
                          >>>If the code was being maintained by Bill possibly. But if a C programmer
                          >>>does not understand something x&1 or shift right/left then they have no
                          >>>business writing in C in a commercial setting.
                          >>>
                          >>But what of pete's first point? I much prefer % and / in the context
                          >>because it expresses a general algorithm.
                          <snip>
                          >I have no problem with his code, but I would suggest that (especially
                          >the shift) the bit test and the shift are obvious to any half decent C
                          >programmer.
                          >
                          Right and I agreed. I wondered if you had anything to add about his
                          first point which is not about whether anyone should or should not be
                          able to read the alternative.
                          If you are talking about the compiler part and the optimisation then
                          yes, of course I agree with him.

                          There is often a misty area with certain code constructs. I would
                          generally go for maintainability over obscure nano second saving
                          techniques. In this case however, >>1 is as clear as /2 for me.

                          However, I remember seeing someone (I think it was Chuck) complaining
                          about

                          while(*d++=*s++ );

                          as being a "misuse" of the language. To me this *IS* C and if you have
                          any issue with it then you should not be programming in C. C is not
                          Pascal or Ada.

                          I have been involved in a lot of large projects with shifting maintainer
                          base. And never once have we advocated programming for the weakest
                          link. We program for competent C programmers not for someone with no
                          programming experience. A good programmer will pick up things very, very
                          quickly. The only real thing I always insisted on was never, ever have
                          conditional result blocks on the same line as the conditional as
                          Falconer seems to favour.

                          e.g

                          if(f){
                          i=f2(i);
                          }

                          is infinitely better than

                          if(f) i=f2(i);

                          I always structure code to faciliate *other people* to set inquisitive
                          break points. But we've all been down that alley here before and I
                          really don't want to hear from the usual suspects about how they once
                          debugged 5000000 lines by simply reading the code as if that somehow
                          meant a debugger was useless for all.


                          Comment

                          • =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?=

                            #14
                            Re: How to print an array of char backward.

                            On Jun 1, 12:22 am, Ben Bacarisse <ben.use...@bsb .me.ukwrote:
                            #define BASE 2
                            #define DIGITS "01"

                            #define DIGITS "01"

                            #define BASE (sizeof digits - 1)

                            :-D

                            To make the trully perfect algorithm for this, you'd need to know:
                            1) Whether there should be trailing zeroes
                            2) Whether it's OK to return a pointer which is a few bytes ahead of
                            the supplied pointer.

                            For example:

                            (Disclaimer: Untested code thrown together in a few minutes)

                            #define DIGITS "0123456789abcd ef"

                            #define BASE (sizeof digits - 1)

                            void Convert(unsigne d const val, char *p)
                            {
                            char *q = p; /* Keep track of the first address */

                            /* --- First write the string backwards --- */

                            do *p++ = DIGITS[val % BASE];
                            while (val /= BASE);

                            *p-- = 0; /* Write the null and point p to the last char */

                            /* --- Now reverse the string --- */

                            for ( ; q p; ++q, --p)
                            {
                            char const temp = *q;
                            *q = *p;
                            *p = temp;
                            }
                            }

                            Comment

                            • Joachim Schmitz

                              #15
                              Re: How to print an array of char backward.

                              Tomás Ó hÉilidhe wrote:
                              On Jun 1, 12:22 am, Ben Bacarisse <ben.use...@bsb .me.ukwrote:
                              >
                              >#define BASE 2
                              >#define DIGITS "01"
                              >
                              >
                              #define DIGITS "01"
                              >
                              #define BASE (sizeof digits - 1)
                              #define BASE (sizeof DIGITS - 1)

                              <snip>

                              Bye, Jojo


                              Comment

                              Working...