Binary number

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

    #1

    Binary number

    How do I display an integer in binary format in C?

    e.g. 4 displayed as "100"


  • infobahn

    #2
    Re: Binary number

    Davey wrote:[color=blue]
    >
    > How do I display an integer in binary format in C?
    >
    > e.g. 4 displayed as "100"[/color]

    Here's one common way to do it:

    1) reserve enough storage for a string that can contain the whole
    result.
    If your integer is an unsigned long int, say, then you know that it
    can't have more than sizeof(long int) * CHAR_BIT value bits, so just
    define an array of char, sizeof(long int) * CHAR_BIT + 1 bytes in
    length.

    2) point to the start of the string.

    3) if the number is even, write '0' through the pointer. Otherwise,
    write '1' through the pointer.

    4) increment the pointer.

    5) divide the number by 2.

    6) if the number is non-zero, continue from step 3).

    7) write '\0' through the pointer, to null-terminate the string.

    8) reverse the string, taking care to leave the terminator in place.

    Comment

    • Joe Wright

      #3
      Re: Binary number

      Davey wrote:[color=blue]
      > How do I display an integer in binary format in C?
      >
      > e.g. 4 displayed as "100"
      >
      >[/color]
      You should try it yourself.

      void bits(uchar b, int n) {
      for (--n; n >= 0; --n)
      putchar((b & 1 << n) ? '1' : '0');
      putchar(' ');
      }

      The above is not a program, but a clue.
      --
      Joe Wright mailto:joewwrig ht@comcast.net
      "Everything should be made as simple as possible, but not simpler."
      --- Albert Einstein ---

      Comment

      • Luke Wu

        #4
        Re: Binary number


        Davey wrote:[color=blue]
        > How do I display an integer in binary format in C?
        >
        > e.g. 4 displayed as "100"[/color]


        #include <stdio.h>
        #include <limits.h>

        #define SHOWBITS(var) bitshow((unsign ed char *)&var, sizeof(var))

        int bitshow(unsigne d char *p, int size)
        {
        int count = 0;
        int byte;
        while(size)
        {
        byte = CHAR_BIT;
        while(byte > 0)
        {
        if(*p & 1 << byte)
        {
        putchar('1');
        count++;
        }
        else putchar('0');

        byte--;
        }
        putchar('\n');
        size--;
        p++;
        }
        return count;
        }

        int main(void)
        {
        int i= 0xFD1;

        SHOWBIT(i); /* returns number of set bits, discarded */

        puts("Press ENTER when done"), getchar();
        return 0;
        }

        Comment

        • Stan Milam

          #5
          Re: Binary number

          Davey wrote:[color=blue]
          > How do I display an integer in binary format in C?
          >
          > e.g. 4 displayed as "100"
          >
          >[/color]
          I thought this sounded familar, so I looked in my archives and sure
          enough, there it was. I can't believe almost 11 years have gone by!

          /*************** *************** *************** *************** ***/
          /* File Id: bin.c. */
          /* Author: Stan Milam. */
          /* Date Written: 28-Apr-94. */
          /* */
          /* This program will print an unsigned integer value entered on*/
          /* the command line in it binary format. */
          /* */
          /*************** *************** *************** *************** ***/

          #include <stdio.h>
          #include <stdlib.h>
          #include <limits.h>

          int main( int argc, char **argv ) {

          unsigned value, rv, mask, i;

          /*************** *************** *************** **************/
          /* Check to see if command line args used. If not give tell*/
          /* user how the program works. */
          /*************** *************** *************** **************/

          if ( argc < 2 ) {
          fputs("Usage: BIN integer_number\ n", stderr);
          return 1;
          }

          /*************** *************** *************** **************/
          /* Determine the mask. Done this way to be portable. Also */
          /* Extract the value from command line. */
          /*************** *************** *************** **************/

          mask = 1 << sizeof(unsigned ) * CHAR_BIT - 1;
          value = (unsigned) strtol(argv[1], NULL, 0);

          /*************** *************** *************** **************/
          /* For each possible bit determine its state and print. */
          /*************** *************** *************** **************/

          for ( i = 0; i < sizeof(unsigned ) * CHAR_BIT; i++ ) {
          rv = (value & mask) >> (sizeof(unsigne d) * CHAR_BIT - 1);
          value <<= 1;
          printf("%d", rv);
          }

          printf("\n");
          return 0;
          }

          Comment

          • CBFalconer

            #6
            Re: Binary number

            Stan Milam wrote:[color=blue]
            > Davey wrote:
            >[color=green]
            >> How do I display an integer in binary format in C?
            >>
            >> e.g. 4 displayed as "100"[/color]
            >
            > I thought this sounded familar, so I looked in my archives and sure
            > enough, there it was. I can't believe almost 11 years have gone by!
            >
            > /*************** *************** *************** *************** ***/
            > /* File Id: bin.c. */
            > /* Author: Stan Milam. */
            > /* Date Written: 28-Apr-94. */
            > /* */
            > /* This program will print an unsigned integer value entered on*/
            > /* the command line in it binary format. */
            > /* */
            > /*************** *************** *************** *************** ***/
            >
            > #include <stdio.h>
            > #include <stdlib.h>
            > #include <limits.h>
            >
            > int main( int argc, char **argv ) {
            >
            > unsigned value, rv, mask, i;
            >
            > /*************** *************** *************** **************/
            > /* Check to see if command line args used. If not give tell*/
            > /* user how the program works. */
            > /*************** *************** *************** **************/[/color]
            .... snip code ...

            Here is something more generalized, with testing code. Also been
            around a while in various guises.

            /* Routines to display values in various bases */
            /* with some useful helper routines. */
            /* by C.B. Falconer, 19 Sept. 2001 */
            /* Released to public domain. Attribution appreciated */

            #include <stdio.h>
            #include <string.h>
            #include <limits.h> /* ULONG_MAX etc. */

            /* =============== ======== */
            /* reverse string in place */
            size_t revstring(char *stg)
            {
            char *last, temp;
            size_t lgh;

            lgh = strlen(stg);
            if (lgh > 1) {
            last = stg + lgh; /* points to '\0' */
            while (last-- > stg) {
            temp = *stg; *stg++ = *last; *last = temp;
            }
            }
            return lgh;
            } /* revstring */

            /* =============== =============== ============== */
            /* Mask and convert digit to hex representation */
            /* Output range is 0..9 and a..f only */
            int hexify(unsigned int value)
            {
            static char hexchars[] = "0123456789abcd ef";

            return (hexchars[value & 0xf]);
            } /* hexify */

            /* =============== =============== =============== ===== */
            /* convert unsigned number to string in various bases */
            /* 2 <= base <= 16, controlled by hexify() */
            /* Returns actual output string length */
            size_t basedisplay(uns igned long number, unsigned int base,
            char *stg, size_t maxlgh)
            {
            char *s;

            /* assert (stg[maxlgh]) is valid storage */
            s = stg;
            if (maxlgh && base)
            do {
            *s = hexify(number % base);
            s++;
            } while (--maxlgh && (number = number / base) );
            *s = '\0';
            revstring(stg);
            return (s - stg);
            } /* basedisplay */

            /* =============== =============== =============== === */
            /* convert signed number to string in various bases */
            /* 2 <= base <= 16, controlled by hexify() */
            /* Returns actual output string length */
            size_t signbasedisplay (long number, unsigned int base,
            char * stg, size_t maxlgh)
            {
            char *s;
            size_t lgh;
            unsigned long n;

            s = stg; lgh = 0;
            n = (unsigned long)number;
            if (maxlgh && (number < 0L)) {
            *s++ = '-';
            maxlgh--;
            n = -(unsigned long)number;
            lgh = 1;
            }
            lgh = lgh + basedisplay(n, base, s, maxlgh);
            return lgh;
            } /* signbaseddispla y */


            /* =============== ===== */
            /* flush to end-of-line */
            int flushln(FILE *f)
            {
            int ch;

            while ('\n' != (ch = fgetc(f)) && (EOF != ch)) /* more */;
            return ch;
            } /* flushln */

            /* ========== END of generically useful routines ============ */

            /* =============== ========== */
            /* Prompt and await <return> */
            static void nexttest(char *prompt)
            {
            static char empty[] = "";

            if (NULL == prompt) prompt = empty;
            printf("\nHit return for next test: %s", prompt);
            fflush(stdout);
            flushln(stdin);
            } /* nexttest */

            /* =============== =============== */
            /* Display a value and its length */
            static void show(char *caption, int sz, char *stg)
            {

            if ((unsigned)sz != strlen(stg))
            printf("Somethi ng is wrong with the sz value\n");
            printf("%s: sz = %2d \"%s\"\n", caption, sz, stg);
            } /* show */

            /* =========== */
            /* exercise it */
            int main(void)
            {
            #define LGH 40
            #define VALUE 1234567890

            char stg[LGH];
            unsigned int base;
            int sz;

            printf("\nExerc ising basedisplay routine\n");
            printf("\nbase sz value\n");
            for (base = 2; base <= 16; base++) {
            sz = (int)basedispla y(VALUE, base, stg, LGH - 1);
            printf("%2d %2d %s\n", base, sz, stg);
            }

            nexttest("ULONG _MAX");
            for (base = 8; base <= 16; base++) {
            sz = (int)basedispla y(ULONG_MAX, base, stg, LGH - 1);
            printf("%2d %2d %s\n", base, sz, stg);
            }

            basedisplay(0, 10, stg, 3);
            printf("\nzero %s\n", stg);

            basedisplay(VAL UE, 10, stg, 3);
            printf("3 lsdigits only, base 10 %s\n", stg);

            printf("\nBad calls:\n");

            sz = (int)basedispla y(VALUE, 10, stg, 0);
            show("0 length field", sz, stg);

            sz = (int)basedispla y(VALUE, 1, stg, 20);
            show("base 1, lgh 20", sz, stg);

            sz = (int)basedispla y(VALUE, 0, stg, 20);
            show("base 0, lgh 20", sz, stg);

            sz = (int)signbasedi splay(-1234, 10, stg, 0);
            show("0 lgh fld, -ve", sz, stg);

            sz = (int)signbasedi splay(-1234, 10, stg, 2);
            show("truncate -1234", sz, stg);

            nexttest("Syste m limits");

            sz = (int)signbasedi splay(SCHAR_MIN , 10, stg, 20);
            show("SCHAR_MIN ", sz, stg);

            sz = (int)signbasedi splay(SCHAR_MAX , 10, stg, 20);
            show("SCHAR_MAX ", sz, stg);

            sz = (int)signbasedi splay(UCHAR_MAX , 10, stg, 20);
            show("UCHAR_MAX ", sz, stg);

            sz = (int)signbasedi splay(CHAR_MIN, 10, stg, 20);
            show("CHAR_MIN ", sz, stg);

            sz = (int)signbasedi splay(CHAR_MAX, 10, stg, 20);
            show("CHAR_MAX ", sz, stg);

            sz = (int)signbasedi splay(MB_LEN_MA X, 10, stg, 20);
            show("MB_LEN_MA X ", sz, stg);

            sz = (int)signbasedi splay(SHRT_MIN, 10, stg, 20);
            show("SHRT_MIN ", sz, stg);

            sz = (int)signbasedi splay(SHRT_MAX, 10, stg, 20);
            show("SHRT_MAX ", sz, stg);

            sz = (int)signbasedi splay(USHRT_MAX , 10, stg, 20);
            show("USHRT_MAX ", sz, stg);

            sz = (int)signbasedi splay(INT_MIN, 10, stg, 20);
            show("INT_MIN ", sz, stg);

            sz = (int)signbasedi splay(INT_MAX, 10, stg, 20);
            show("INT_MAX ", sz, stg);

            sz = (int)signbasedi splay(INT_MAX, 10, stg, 20);
            show("INT_MAX ", sz, stg);

            sz = (int) basedisplay(UIN T_MAX, 10, stg, 20);
            show("UINT_MAX ", sz, stg);

            sz = (int)signbasedi splay(LONG_MIN, 10, stg, 20);
            show("LONG_MIN ", sz, stg);

            sz = (int)signbasedi splay(LONG_MAX, 10, stg, 20);
            show("LONG_MAX ", sz, stg);

            sz = (int) basedisplay(ULO NG_MAX, 10, stg, 20);
            show("ULONG_MAX ", sz, stg);

            nexttest("DONE" );
            return 0;
            } /* main */

            --
            "If you want to post a followup via groups.google.c om, don't use
            the broken "Reply" link at the bottom of the article. Click on
            "show options" at the top of the article, then click on the
            "Reply" at the bottom of the article headers." - Keith Thompson


            Comment

            • Peter Nilsson

              #7
              Re: Binary number

              Davey wrote:[color=blue]
              > How do I display an integer in binary format in C?
              >
              > e.g. 4 displayed as "100"[/color]

              void dump(unsigned x)
              {
              unsigned m;
              if (x == 0) m = 1;
              else for (m = -1u/2+1; !(x & m); m >>= 1) ;
              do { putchar('0' + !!(x & m)); } while (m >>= 1);
              }

              --
              Peter

              Comment

              • Stan Milam

                #8
                Re: Binary number

                CBFalconer wrote:[color=blue]
                > Stan Milam wrote:
                >[color=green]
                >>Davey wrote:
                >>
                >>[color=darkred]
                >>>How do I display an integer in binary format in C?
                >>>
                >>>e.g. 4 displayed as "100"[/color]
                >>
                >>I thought this sounded familar, so I looked in my archives and sure
                >>enough, there it was. I can't believe almost 11 years have gone by!
                >>
                >>/*************** *************** *************** *************** ***/
                >>/* File Id: bin.c. */
                >>/* Author: Stan Milam. */
                >>/* Date Written: 28-Apr-94. */
                >>/* */
                >>/* This program will print an unsigned integer value entered on*/
                >>/* the command line in it binary format. */
                >>/* */
                >>/*************** *************** *************** *************** ***/
                >>
                >>#include <stdio.h>
                >>#include <stdlib.h>
                >>#include <limits.h>
                >>
                >>int main( int argc, char **argv ) {
                >>
                >> unsigned value, rv, mask, i;
                >>
                >> /*************** *************** *************** **************/
                >> /* Check to see if command line args used. If not give tell*/
                >> /* user how the program works. */
                >> /*************** *************** *************** **************/[/color]
                >
                > ... snip code ...
                >
                > Here is something more generalized, with testing code. Also been
                > around a while in various guises.
                >
                > /* Routines to display values in various bases */
                > /* with some useful helper routines. */
                > /* by C.B. Falconer, 19 Sept. 2001 */
                > /* Released to public domain. Attribution appreciated */
                >
                > #include <stdio.h>
                > #include <string.h>
                > #include <limits.h> /* ULONG_MAX etc. */
                >
                > /* =============== ======== */
                > /* reverse string in place */
                > size_t revstring(char *stg)
                > {
                > char *last, temp;
                > size_t lgh;
                >
                > lgh = strlen(stg);
                > if (lgh > 1) {
                > last = stg + lgh; /* points to '\0' */
                > while (last-- > stg) {
                > temp = *stg; *stg++ = *last; *last = temp;
                > }
                > }
                > return lgh;
                > } /* revstring */
                >
                > /* =============== =============== ============== */
                > /* Mask and convert digit to hex representation */
                > /* Output range is 0..9 and a..f only */
                > int hexify(unsigned int value)
                > {
                > static char hexchars[] = "0123456789abcd ef";
                >
                > return (hexchars[value & 0xf]);
                > } /* hexify */
                >
                > /* =============== =============== =============== ===== */
                > /* convert unsigned number to string in various bases */
                > /* 2 <= base <= 16, controlled by hexify() */
                > /* Returns actual output string length */
                > size_t basedisplay(uns igned long number, unsigned int base,
                > char *stg, size_t maxlgh)
                > {
                > char *s;
                >
                > /* assert (stg[maxlgh]) is valid storage */
                > s = stg;
                > if (maxlgh && base)
                > do {
                > *s = hexify(number % base);
                > s++;
                > } while (--maxlgh && (number = number / base) );
                > *s = '\0';
                > revstring(stg);
                > return (s - stg);
                > } /* basedisplay */
                >
                > /* =============== =============== =============== === */
                > /* convert signed number to string in various bases */
                > /* 2 <= base <= 16, controlled by hexify() */
                > /* Returns actual output string length */
                > size_t signbasedisplay (long number, unsigned int base,
                > char * stg, size_t maxlgh)
                > {
                > char *s;
                > size_t lgh;
                > unsigned long n;
                >
                > s = stg; lgh = 0;
                > n = (unsigned long)number;
                > if (maxlgh && (number < 0L)) {
                > *s++ = '-';
                > maxlgh--;
                > n = -(unsigned long)number;
                > lgh = 1;
                > }
                > lgh = lgh + basedisplay(n, base, s, maxlgh);
                > return lgh;
                > } /* signbaseddispla y */
                >
                >
                > /* =============== ===== */
                > /* flush to end-of-line */
                > int flushln(FILE *f)
                > {
                > int ch;
                >
                > while ('\n' != (ch = fgetc(f)) && (EOF != ch)) /* more */;
                > return ch;
                > } /* flushln */
                >
                > /* ========== END of generically useful routines ============ */
                >
                > /* =============== ========== */
                > /* Prompt and await <return> */
                > static void nexttest(char *prompt)
                > {
                > static char empty[] = "";
                >
                > if (NULL == prompt) prompt = empty;
                > printf("\nHit return for next test: %s", prompt);
                > fflush(stdout);
                > flushln(stdin);
                > } /* nexttest */
                >
                > /* =============== =============== */
                > /* Display a value and its length */
                > static void show(char *caption, int sz, char *stg)
                > {
                >
                > if ((unsigned)sz != strlen(stg))
                > printf("Somethi ng is wrong with the sz value\n");
                > printf("%s: sz = %2d \"%s\"\n", caption, sz, stg);
                > } /* show */
                >
                > /* =========== */
                > /* exercise it */
                > int main(void)
                > {
                > #define LGH 40
                > #define VALUE 1234567890
                >
                > char stg[LGH];
                > unsigned int base;
                > int sz;
                >
                > printf("\nExerc ising basedisplay routine\n");
                > printf("\nbase sz value\n");
                > for (base = 2; base <= 16; base++) {
                > sz = (int)basedispla y(VALUE, base, stg, LGH - 1);
                > printf("%2d %2d %s\n", base, sz, stg);
                > }
                >
                > nexttest("ULONG _MAX");
                > for (base = 8; base <= 16; base++) {
                > sz = (int)basedispla y(ULONG_MAX, base, stg, LGH - 1);
                > printf("%2d %2d %s\n", base, sz, stg);
                > }
                >
                > basedisplay(0, 10, stg, 3);
                > printf("\nzero %s\n", stg);
                >
                > basedisplay(VAL UE, 10, stg, 3);
                > printf("3 lsdigits only, base 10 %s\n", stg);
                >
                > printf("\nBad calls:\n");
                >
                > sz = (int)basedispla y(VALUE, 10, stg, 0);
                > show("0 length field", sz, stg);
                >
                > sz = (int)basedispla y(VALUE, 1, stg, 20);
                > show("base 1, lgh 20", sz, stg);
                >
                > sz = (int)basedispla y(VALUE, 0, stg, 20);
                > show("base 0, lgh 20", sz, stg);
                >
                > sz = (int)signbasedi splay(-1234, 10, stg, 0);
                > show("0 lgh fld, -ve", sz, stg);
                >
                > sz = (int)signbasedi splay(-1234, 10, stg, 2);
                > show("truncate -1234", sz, stg);
                >
                > nexttest("Syste m limits");
                >
                > sz = (int)signbasedi splay(SCHAR_MIN , 10, stg, 20);
                > show("SCHAR_MIN ", sz, stg);
                >
                > sz = (int)signbasedi splay(SCHAR_MAX , 10, stg, 20);
                > show("SCHAR_MAX ", sz, stg);
                >
                > sz = (int)signbasedi splay(UCHAR_MAX , 10, stg, 20);
                > show("UCHAR_MAX ", sz, stg);
                >
                > sz = (int)signbasedi splay(CHAR_MIN, 10, stg, 20);
                > show("CHAR_MIN ", sz, stg);
                >
                > sz = (int)signbasedi splay(CHAR_MAX, 10, stg, 20);
                > show("CHAR_MAX ", sz, stg);
                >
                > sz = (int)signbasedi splay(MB_LEN_MA X, 10, stg, 20);
                > show("MB_LEN_MA X ", sz, stg);
                >
                > sz = (int)signbasedi splay(SHRT_MIN, 10, stg, 20);
                > show("SHRT_MIN ", sz, stg);
                >
                > sz = (int)signbasedi splay(SHRT_MAX, 10, stg, 20);
                > show("SHRT_MAX ", sz, stg);
                >
                > sz = (int)signbasedi splay(USHRT_MAX , 10, stg, 20);
                > show("USHRT_MAX ", sz, stg);
                >
                > sz = (int)signbasedi splay(INT_MIN, 10, stg, 20);
                > show("INT_MIN ", sz, stg);
                >
                > sz = (int)signbasedi splay(INT_MAX, 10, stg, 20);
                > show("INT_MAX ", sz, stg);
                >
                > sz = (int)signbasedi splay(INT_MAX, 10, stg, 20);
                > show("INT_MAX ", sz, stg);
                >
                > sz = (int) basedisplay(UIN T_MAX, 10, stg, 20);
                > show("UINT_MAX ", sz, stg);
                >
                > sz = (int)signbasedi splay(LONG_MIN, 10, stg, 20);
                > show("LONG_MIN ", sz, stg);
                >
                > sz = (int)signbasedi splay(LONG_MAX, 10, stg, 20);
                > show("LONG_MAX ", sz, stg);
                >
                > sz = (int) basedisplay(ULO NG_MAX, 10, stg, 20);
                > show("ULONG_MAX ", sz, stg);
                >
                > nexttest("DONE" );
                > return 0;
                > } /* main */
                >[/color]

                CB, keep it small, keep it simple, keep it readable and you will be more
                productive and live longer.

                Stan.

                Comment

                • Peter Nilsson

                  #9
                  Re: Binary number

                  Stan Milam wrote:[color=blue]
                  > CBFalconer wrote:[/color]

                  <snip>
                  [color=blue]
                  > CB, keep it small, keep it simple, keep it readable and you
                  > will be more productive and live longer.[/color]

                  Any reason why you quoted the whole thing?

                  Your post would be more productive if you pointed out the
                  issue with LONG_MIN within CBF's code. ;)

                  --
                  Peter

                  Comment

                  • CBFalconer

                    #10
                    Re: Binary number

                    Peter Nilsson wrote:[color=blue]
                    > Stan Milam wrote:[color=green]
                    >> CBFalconer wrote:[/color]
                    >
                    > <snip>
                    >[color=green]
                    >> CB, keep it small, keep it simple, keep it readable and you
                    >> will be more productive and live longer.[/color]
                    >
                    > Any reason why you quoted the whole thing?
                    >
                    > Your post would be more productive if you pointed out the
                    > issue with LONG_MIN within CBF's code. ;)[/color]

                    What issue? A value of LONG_MIN is immediately converted to an
                    unsigned long with a '-' sign emitted.

                    --
                    "If you want to post a followup via groups.google.c om, don't use
                    the broken "Reply" link at the bottom of the article. Click on
                    "show options" at the top of the article, then click on the
                    "Reply" at the bottom of the article headers." - Keith Thompson


                    Comment

                    • Peter Nilsson

                      #11
                      Re: Binary number

                      CBFalconer wrote:[color=blue]
                      > ...
                      > What issue? A value of LONG_MIN is immediately converted to an
                      > unsigned long with a '-' sign emitted.[/color]

                      The conversion of LONG_MIN to unsigned long may yield 0.

                      It's not likely to on any implementation in existance, but
                      the standard allows it. [Genuine strictly conforming itoa
                      functions have previously been posted to clc.]

                      --
                      Peter

                      Comment

                      • CBFalconer

                        #12
                        Re: Binary number

                        Peter Nilsson wrote:[color=blue]
                        > CBFalconer wrote:[color=green]
                        >> ...
                        >> What issue? A value of LONG_MIN is immediately converted to an
                        >> unsigned long with a '-' sign emitted.[/color]
                        >
                        > The conversion of LONG_MIN to unsigned long may yield 0.
                        >
                        > It's not likely to on any implementation in existance, but
                        > the standard allows it. [Genuine strictly conforming itoa
                        > functions have previously been posted to clc.][/color]

                        I see no way for a non-zero integer to be converted to zero. Show
                        me. Remember that ULONG_MAX has to be odd, as implied by the
                        imposed weighted bit construction.


                        --
                        Some informative links:
                        news:news.annou nce.newusers
                        Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!






                        Comment

                        • Michael

                          #13
                          Re: Binary number

                          1. use lib function

                          #include <stdlib.h>
                          #include <stdio.h>

                          int main(void)
                          {
                          int number = 4;
                          char string[25];

                          itoa(number, string, 10);
                          printf("integer = %d string = %s\n", number, string);
                          return 0;
                          }



                          2. write a function like itoa

                          char* itoap(int val, int base)
                          {
                          static char buf[32] = {0};
                          int i = 30;
                          for(; val && i ; --i, val /= base){
                          buf[i] ="0123456789abc def"[val % base];
                          printf("%c\n",b uf[i]);
                          }
                          return &buf[i+1];
                          }





                          "Davey" <davey@hello.co m> дÈëÏû
                          Ï¢ÐÂÎÅ:37p6inF5 e8reoU1@individ ual.net...[color=blue]
                          > How do I display an integer in binary format in C?
                          >
                          > e.g. 4 displayed as "100"
                          >[/color]


                          Comment

                          • Michael

                            #14
                            Re: Binary number

                            I'am sorry!
                            itoa(number,str ing,10) should be corrected to itoa(number,str ing,2)

                            "Michael" <qq_qiutao@126. com> дÈëÏûÏ¢ÐÂÎÅ:cv f4k3$3af$1@news .yaako.com...[color=blue]
                            > 1. use lib function
                            >
                            > #include <stdlib.h>
                            > #include <stdio.h>
                            >
                            > int main(void)
                            > {
                            > int number = 4;
                            > char string[25];
                            >
                            > itoa(number, string, 10);
                            > printf("integer = %d string = %s\n", number, string);
                            > return 0;
                            > }
                            >
                            >
                            >
                            > 2. write a function like itoa
                            >
                            > char* itoap(int val, int base)
                            > {
                            > static char buf[32] = {0};
                            > int i = 30;
                            > for(; val && i ; --i, val /= base){
                            > buf[i] ="0123456789abc def"[val % base];
                            > printf("%c\n",b uf[i]);
                            > }
                            > return &buf[i+1];
                            > }
                            >
                            >
                            >
                            >
                            >
                            > "Davey" <davey@hello.co m> дÈëÏû
                            > Ï¢ÐÂÎÅ:37p6inF5 e8reoU1@individ ual.net...[color=green]
                            >> How do I display an integer in binary format in C?
                            >>
                            >> e.g. 4 displayed as "100"
                            >>[/color]
                            >
                            >[/color]


                            Comment

                            • Chris Croughton

                              #15
                              Re: Binary number

                              On Tue, 22 Feb 2005 19:14:52 +0800, Michael
                              <qq_qiutao@126. com> wrote:
                              [color=blue]
                              > 1. use lib function
                              >
                              > #include <stdlib.h>
                              > #include <stdio.h>
                              >
                              > int main(void)
                              > {
                              > int number = 4;
                              > char string[25];
                              >
                              > itoa(number, string, 10);[/color]

                              There is no such function in Standard C.
                              [color=blue]
                              > printf("integer = %d string = %s\n", number, string);
                              > return 0;
                              > }
                              >
                              >
                              > 2. write a function like itoa
                              >
                              > char* itoap(int val, int base)
                              > {
                              > static char buf[32] = {0};[/color]

                              How do you know that 32 characters is enough? It isn't, even with 32
                              bit values. The correct size should be something like:

                              #include <limits.h>

                              #define MAX_DIGITS (sizeof(val) * CHAR_BIT)

                              then define the buffer as

                              static char buf[MAX_DIGITS+1] = {0};
                              [color=blue]
                              > int i = 30;[/color]

                              and that should initialise i to MAX_DIGITS.
                              [color=blue]
                              > for(; val && i ; --i, val /= base){
                              > buf[i] ="0123456789abc def"[val % base];
                              > printf("%c\n",b uf[i]);
                              > }
                              > return &buf[i+1];
                              > }[/color]

                              Also, it would be a good idea to test base for being greater than 1 and
                              no greater than 16 and return some sort of error (possibly a null
                              pointer, possibly fill the buffer with stars, or just assert()).

                              Chris C

                              Comment

                              Working...