print binary representation

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

    print binary representation

    Hi!

    How can I output value of char or int in binary form with printf(); ?

    thanx in advance
  • =?utf-8?B?SGFyYWxkIHZhbiBExLNr?=

    #2
    Re: print binary representation

    Carramba wrote:
    Hi!
    >
    How can I output value of char or int in binary form with printf(); ?
    >
    thanx in advance
    There is no standard format specifier for binary form. You will have
    to do the conversion manually, testing each bit from highest to
    lowest, printing '0' if it's not set, and '1' if it is.

    Comment

    • jaysome

      #3
      Re: print binary representation

      On Sat, 24 Mar 2007 08:55:36 +0100, Carramba <user@example.n etwrote:
      >Hi!
      >
      >How can I output value of char or int in binary form with printf(); ?
      >
      >thanx in advance
      The C Standards do not define a conversion specifier for printf() to
      output in binary. The only portable way to do this is to roll your
      own. Here's a start:

      printf("%s\n", int_to_binary_s tring(my_int));

      Make sure when you implement int_to_binary_s tring() that it works with
      most desktop targets where sizeof(int) * CHAR_BIT = 32 as well on many
      embedded targets where sizeof(int) * CHAR_BIT = 16.

      Best regards
      --
      jay

      Comment

      • Beej Jorgensen

        #4
        Re: print binary representation

        Carramba <user@example.n etwrote:
        >How can I output value of char or int in binary form with printf(); ?




        HTH,
        -Beej

        Comment

        • Malcolm McLean

          #5
          Re: print binary representation


          "Carramba" <user@example.n etwrote in message
          news:4604d5ca$0 $488$cc7c7865@n ews.luth.se...
          Hi!
          >
          How can I output value of char or int in binary form with printf(); ?
          >
          thanx in advance
          #include <limits.h>
          /*
          convert machine number to human-readable binary string.
          Returns: pointer to static string overwritten with each call.
          */
          char *itob(int x)
          {
          static char buff[sizeof(int) * CHAR_BIT + 1];
          int i;
          int j = sizeof(int) * CHAR_BIT - 1;

          buff[j] = 0;
          for(i=0;i<sizeo f(int) * CHAR_BIT; i++)
          {
          if(x & (1 << i))
          buff[j] = '1';
          else
          buff[j] = '0';
          j--;
          }
          return buff;
          }

          Call

          int x = 100;
          printf("%s", itob(x));

          You might want something more elaborate to cut leading zeroes or handle
          negative numbers.

          Comment

          • Carramba

            #6
            Re: print binary representation

            Harald van Dijk wrote:
            Carramba wrote:
            >Hi!
            >>
            >How can I output value of char or int in binary form with printf(); ?
            >>
            >thanx in advance
            There is no standard format specifier for binary form. You will have
            to do the conversion manually, testing each bit from highest to
            lowest, printing '0' if it's not set, and '1' if it is.
            thanx, maybe you have so suggestion or link for further reading on how
            to do it?

            Comment

            • Carramba

              #7
              Re: print binary representation

              thanx ! have few questions about this code :)
              Malcolm McLean wrote:
              >
              "Carramba" <user@example.n etwrote in message
              news:4604d5ca$0 $488$cc7c7865@n ews.luth.se...
              >Hi!
              >>
              >How can I output value of char or int in binary form with printf(); ?
              >>
              >thanx in advance
              #include <limits.h>
              /*
              convert machine number to human-readable binary string.
              Returns: pointer to static string overwritten with each call.
              */
              char *itob(int x)
              {
              static char buff[sizeof(int) * CHAR_BIT + 1];
              why sizeof(int) * CHAR_BIT + 1 ? what does it mean?
              int i;
              int j = sizeof(int) * CHAR_BIT - 1;
              why sizeof(int) * CHAR_BIT - 1 ? what does it mean?
              >
              buff[j] = 0;
              for(i=0;i<sizeo f(int) * CHAR_BIT; i++)
              {
              if(x & (1 << i))
              buff[j] = '1';
              else
              buff[j] = '0';
              j--;
              }
              return buff;
              }
              >
              Call
              >
              int x = 100;
              printf("%s", itob(x));
              >
              You might want something more elaborate to cut leading zeroes or handle
              negative numbers.

              Comment

              • =?utf-8?B?SGFyYWxkIHZhbiBExLNr?=

                #8
                Re: print binary representation

                Carramba wrote:
                Harald van Dijk wrote:
                Carramba wrote:
                Hi!
                >
                How can I output value of char or int in binary form with printf(); ?
                >
                thanx in advance
                There is no standard format specifier for binary form. You will have
                to do the conversion manually, testing each bit from highest to
                lowest, printing '0' if it's not set, and '1' if it is.
                thanx, maybe you have so suggestion or link for further reading on how
                to do it?
                Others have given code already, but here's mine anyway:

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

                void print_char_bina ry(char val)
                {
                char mask;

                if(CHAR_MIN < 0)
                {
                if(val < 0
                || val == 0 && val & CHAR_MAX)
                putchar('1');
                else
                putchar('0');
                }

                for(mask = (CHAR_MAX >1) + 1; mask != 0; mask >>= 1)
                if(val & mask)
                putchar('1');
                else
                putchar('0');
                }

                void print_int_binar y(int val)
                {
                int mask;

                if(val < 0
                || val == 0 && val & INT_MAX)
                putchar('1');
                else
                putchar('0');

                for(mask = (INT_MAX >1) + 1; mask != 0; mask >>= 1)
                if(val & mask)
                putchar('1');
                else
                putchar('0');
                }

                Comment

                • pete

                  #9
                  Re: print binary representation

                  Carramba wrote:
                  >
                  Hi!
                  >
                  How can I output value of char or int in binary form with printf(); ?
                  >
                  thanx in advance
                  /* BEGIN output from new.c */

                  1 = 00000001
                  2 = 00000010
                  3 = 00000011
                  4 = 00000100
                  5 = 00000101
                  6 = 00000110
                  7 = 00000111
                  8 = 00001000
                  9 = 00001001
                  10 = 00001010
                  11 = 00001011
                  12 = 00001100
                  13 = 00001101
                  14 = 00001110
                  15 = 00001111
                  16 = 00010000
                  17 = 00010001
                  18 = 00010010
                  19 = 00010011
                  20 = 00010100

                  /* END output from new.c */

                  /* BEGIN new.c */

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

                  #define STRING "%2d = %s\n"
                  #define E_TYPE char
                  #define P_TYPE int
                  #define INITIAL 1
                  #define FINAL 20
                  #define INC(E) (++(E))

                  typedef E_TYPE e_type;
                  typedef P_TYPE p_type;

                  void bitstr(char *str, const void *obj, size_t n);

                  int main(void)
                  {
                  e_type e;
                  char ebits[CHAR_BIT * sizeof e + 1];

                  puts("\n/* BEGIN output from new.c */\n");
                  e = INITIAL;
                  bitstr(ebits, &e, sizeof e);
                  printf(STRING, (p_type)e, ebits);
                  while (FINAL e) {
                  INC(e);
                  bitstr(ebits, &e, sizeof e);
                  printf(STRING, (p_type)e, ebits);
                  }
                  puts("\n/* END output from new.c */");
                  return 0;
                  }

                  void bitstr(char *str, const void *obj, size_t n)
                  {
                  unsigned mask;
                  const unsigned char *byte = obj;

                  while (n-- != 0) {
                  mask = ((unsigned char)-1 >1) + 1;
                  do {
                  *str++ = (char)(mask & byte[n] ? '1' : '0');
                  mask >>= 1;
                  } while (mask != 0);
                  }
                  *str = '\0';
                  }

                  /* END new.c */


                  --
                  pete

                  Comment

                  • Joachim Schmitz

                    #10
                    Re: print binary representation

                    "Carramba" <user@example.n etschrieb im Newsbeitrag
                    news:46050ac1$0 $492$cc7c7865@n ews.luth.se...
                    thanx ! have few questions about this code :)
                    Malcolm McLean wrote:
                    >>
                    >"Carramba" <user@example.n etwrote in message
                    >news:4604d5ca$ 0$488$cc7c7865@ news.luth.se...
                    >>Hi!
                    >>>
                    >>How can I output value of char or int in binary form with printf(); ?
                    >>>
                    >>thanx in advance
                    >#include <limits.h>
                    >/*
                    > convert machine number to human-readable binary string.
                    > Returns: pointer to static string overwritten with each call.
                    >*/
                    >char *itob(int x)
                    >{
                    > static char buff[sizeof(int) * CHAR_BIT + 1];
                    why sizeof(int) * CHAR_BIT + 1 ? what does it mean?
                    If you want to put an in't binary representation ionto a string you need
                    that much space.
                    On many implementations sizeof(int) is 4 and CHAR_BIT is 8, so you'd need an
                    array of 33 chars (including the teminating null byte).

                    I'd use sizeof(x) instead of sizeof(int), that way you can easily change the
                    function to work on e.g. long long
                    > int i;
                    > int j = sizeof(int) * CHAR_BIT - 1;
                    why sizeof(int) * CHAR_BIT - 1 ? what does it mean?
                    Arrays count from 0 to n and the terminating null byte isn't needed , so the
                    index goes from 0 to 31 (assuming the same sizes as above)
                    > buff[j] = 0;
                    > for(i=0;i<sizeo f(int) * CHAR_BIT; i++)
                    > {
                    > if(x & (1 << i))
                    > buff[j] = '1';
                    >else
                    > buff[j] = '0';
                    >j--;
                    > }
                    > return buff;
                    >}
                    >>
                    >Call
                    >>
                    >int x = 100;
                    >printf("%s", itob(x));
                    >>
                    >You might want something more elaborate to cut leading zeroes or handle
                    >negative numbers
                    Bye, Jojo.


                    Comment

                    • pete

                      #11
                      Re: print binary representation

                      Malcolm McLean wrote:
                      for(i=0;i<sizeo f(int) * CHAR_BIT; i++)
                      {
                      if(x & (1 << i))
                      There are some problems with that shift expression.

                      (1 << sizeof(int) * CHAR_BIT - 1) is undefined.

                      --
                      pete

                      Comment

                      • Malcolm McLean

                        #12
                        Re: print binary representation


                        "pete" <pfiland@mindsp ring.comwrote in message
                        Malcolm McLean wrote:
                        >
                        > for(i=0;i<sizeo f(int) * CHAR_BIT; i++)
                        > {
                        > if(x & (1 << i))
                        >
                        There are some problems with that shift expression.
                        >
                        (1 << sizeof(int) * CHAR_BIT - 1) is undefined.
                        >
                        The function should take an unsigned int. However I didn't want to add that
                        complication for the OP. It should work OK on almost every platform.
                        --
                        Free games and programming goodies.


                        Comment

                        • pete

                          #13
                          Re: print binary representation

                          Malcolm McLean wrote:
                          >
                          "pete" <pfiland@mindsp ring.comwrote in message
                          (1 << sizeof(int) * CHAR_BIT - 1) is undefined.
                          The function should take an unsigned int.
                          That makes no difference.
                          The evaluation of (1 << sizeof(int) * CHAR_BIT - 1)
                          in a program is always undefined,
                          and prevents a program from being a "correct program".
                          (1 << sizeof(int) * CHAR_BIT - 1) can't be a positive value.
                          However I didn't want to add that
                          complication for the OP.
                          That expression would be perfect to use as
                          an example of how not to write code.
                          It should work OK on almost every platform.
                          (1u << sizeof(int) * CHAR_BIT - 1) is defined.

                          Your initial value of j is also wrong:

                          int j = sizeof(int) * CHAR_BIT - 1;

                          buff[j] = 0;
                          for(i=0;i<sizeo f(int) * CHAR_BIT; i++)
                          {
                          if(x & (1 << i))
                          buff[j] = '1';
                          else
                          buff[j] = '0';

                          As you can see in your code above,
                          the first side effect of the for loop,
                          is to overwrite the null terminator.


                          /* BEGIN new.c */

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

                          char *itob(unsigned x);

                          int main(void)
                          {
                          printf("%s\n", itob(100));
                          return 0;
                          }

                          char *itob(unsigned x)
                          {
                          unsigned i;
                          unsigned j;
                          static char buff[sizeof x * CHAR_BIT + 1];

                          j = sizeof x * CHAR_BIT;
                          buff[j--] = '\0';
                          for (i = 0; i < sizeof x * CHAR_BIT; i++) {
                          if (x & (1u << i)) {
                          buff[j--] = '1';
                          } else {
                          buff[j--] = '0';
                          }
                          if ((1u << i) == UINT_MAX / 2 + 1) {
                          break;
                          }
                          }
                          while (i++ < sizeof x * CHAR_BIT) {
                          buff[j--] = '0';
                          }
                          return buff;
                          }

                          /* END new.c */


                          --
                          pete

                          Comment

                          • Malcolm McLean

                            #14
                            Re: print binary representation

                            "pete" <pfilandr@minds pring.comwrote in message
                            Malcolm McLean wrote:
                            >>
                            >"pete" <pfiland@mindsp ring.comwrote in message
                            >
                            (1 << sizeof(int) * CHAR_BIT - 1) is undefined.
                            >
                            >The function should take an unsigned int.
                            >
                            That makes no difference.
                            The evaluation of (1 << sizeof(int) * CHAR_BIT - 1)
                            in a program is always undefined,
                            and prevents a program from being a "correct program".
                            (1 << sizeof(int) * CHAR_BIT - 1) can't be a positive value.
                            >
                            >However I didn't want to add that
                            >complication for the OP.
                            >
                            That expression would be perfect to use as
                            an example of how not to write code.
                            >
                            >It should work OK on almost every platform.
                            >
                            (1u << sizeof(int) * CHAR_BIT - 1) is defined.
                            >
                            Your initial value of j is also wrong:
                            >
                            int j = sizeof(int) * CHAR_BIT - 1;
                            >
                            buff[j] = 0;
                            for(i=0;i<sizeo f(int) * CHAR_BIT; i++)
                            {
                            if(x & (1 << i))
                            buff[j] = '1';
                            else
                            buff[j] = '0';
                            >
                            As you can see in your code above,
                            the first side effect of the for loop,
                            is to overwrite the null terminator.
                            >
                            >
                            /* BEGIN new.c */
                            >
                            #include <stdio.h>
                            #include <limits.h>
                            >
                            char *itob(unsigned x);
                            >
                            int main(void)
                            {
                            printf("%s\n", itob(100));
                            return 0;
                            }
                            >
                            char *itob(unsigned x)
                            {
                            unsigned i;
                            unsigned j;
                            static char buff[sizeof x * CHAR_BIT + 1];
                            >
                            j = sizeof x * CHAR_BIT;
                            buff[j--] = '\0';
                            for (i = 0; i < sizeof x * CHAR_BIT; i++) {
                            if (x & (1u << i)) {
                            buff[j--] = '1';
                            } else {
                            buff[j--] = '0';
                            }
                            if ((1u << i) == UINT_MAX / 2 + 1) {
                            break;
                            }
                            }
                            while (i++ < sizeof x * CHAR_BIT) {
                            buff[j--] = '0';
                            }
                            return buff;
                            }
                            >
                            /* END new.c */
                            >
                            unsigned integers aren't allowed padding bits so you don't need all that
                            complication.
                            A pathological platform might break on the expression 1 << int bits - 1,
                            agreed. To be strictly correct we need to do the calculations in unsigned
                            integers, but I've explained why I didn't do that.
                            The off by one error in writing the nul was a slip. Of course I didn't
                            realise because the static array was zero intilaised anyway. So well
                            spotted.
                            --
                            Free games and programming goodies.


                            Comment

                            • pete

                              #15
                              Re: print binary representation

                              Malcolm McLean wrote:
                              unsigned integers aren't allowed padding bits
                              Wrong again.
                              unsigned char isn't allowed padding bits.
                              UINT_MAX is allowed to be as low as INT_MAX,
                              and you can't achieve that without padding bits
                              in the unsigned int type.

                              --
                              pete

                              Comment

                              Working...