print binary

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kapteyn's Star

    print binary

    hi group,
    i try to compile code below but my compiler is failing. it tells:-
    printbin.c: In function ‘main’:
    printbin.c:9: error: invalid operands to binary & i am not able to
    understand what it mean. how to correct fault? please help i'm only new to
    C.

    #include<stdio. h>
    #include<math.h >
    main()
    {
    int val,npow;
    printf("enter value:");
    scanf("%d",&val );
    for(npow=31;npo w>-1;--npow){
    if(val&pow(2,np ow))putchar(1);
    else putchar(0);
    }
    }
  • Don Bruder

    #2
    Re: print binary

    In article <g3fcs1$b64$1@a ioe.org>,
    Kapteyn's Star <invalid@invali d.invalidwrote:
    hi group,
    i try to compile code below but my compiler is failing. it tells:-
    printbin.c: In function 'main':
    printbin.c:9: error: invalid operands to binary & i am not able to
    understand what it mean. how to correct fault? please help i'm only new to
    C.
    >
    #include<stdio. h>
    #include<math.h >
    main()
    {
    int val,npow;
    printf("enter value:");
    scanf("%d",&val );
    for(npow=31;npo w>-1;--npow){
    if(val&pow(2,np ow))putchar(1);
    else putchar(0);
    }
    }
    Among other problems, it looks as though you're trying to "be too
    clever"...

    Break it down further into individual steps instead of trying to be so
    "clever" by cramming it all on one basically unreadable line. Whitespace
    is free and unlimited, and makes a world of difference in readability.
    Which, in turn, makes trying to spot problems easier. Ditto local
    variables for intermediate steps.

    for (npow=...)
    {
    PowerVal = pow(2, npow);
    TheBit = val & PowerVal;
    if (TheBit)
    putchar('1');
    else
    putchar('0');
    }
    etc...

    One of the "other problems":
    "putchar(1) " is going to try to print the character represented by ASCII
    code 1, which is almost guaranteed to NOT be "the digit 1", as you're
    hoping for... I'm betting what actually comes out will be either some
    unreadable graphic char, or an invisible representation of "Control-A",
    but exactly what will get printed is going to be platform dependent.

    You're also assuming that an int is 32 bits long. Which isn't always
    true, and can land you in a world of "Why isn't this working?!?!?"
    hurt...

    --
    Don Bruder - dakidd@sonic.ne t - If your "From:" address isn't on my whitelist,
    or the subject of the message doesn't contain the exact text "PopperAndShado w"
    somewhere, any message sent to this address will go in the garbage without my
    ever knowing it arrived. Sorry... <http://www.sonic.net/~dakiddfor more info

    Comment

    • Robert Gamble

      #3
      Re: print binary

      On Jun 20, 12:49 am, Kapteyn's Star <inva...@invali d.invalidwrote:
      hi group,
      i try to compile code below but my compiler is failing. it tells:-
      printbin.c: In function ‘main’:
      printbin.c:9: error: invalid operands to binary & i am not able to
      understand what it mean. how to correct fault? please help i'm only new to
      C.
      >
      #include<stdio. h>
      #include<math.h >
      main()
      {
          int val,npow;
          printf("enter value:");
          scanf("%d",&val );
          for(npow=31;npo w>-1;--npow){
              if(val&pow(2,np ow))putchar(1);
              else putchar(0);
          }
      >
      }
      >
      >
      The pow() function returns a double value, the binary & operator works
      only with integer operators. You can cast the return value of pow()
      to int, or use a more efficient method to do your bit checking. Your
      putchar calls should be changed to putchar('1') and putchar('0')
      respectively, putchar(1) will print the character with the numeric
      value of 1 as opposed to the character that represents the number 1.
      You should also print a newline at the end out your output. You
      should have a correct prototype for main() and a little more liberal
      use of whitespace would be welcome. Here is a revised version:

      #include <stdio.h>
      #include <math.h>

      int main(void)
      {
      int val, npow;

      printf("enter value: ");
      scanf("%d", &val);

      for (npow = 31; npow -1; --npow) {
      (val & (int) pow(2, npow)) ? putchar('1') : putchar('0');
      }
      putchar('\n');

      return 0;
      }

      Like the original, this assumes a 32-bit int and the multiple calls to
      pow() are very inefficient. Instead of "val & (int) pow(2, npow)" try
      "val & 1<<npow".

      --
      Robert Gamble

      Comment

      • Flash Gordon

        #4
        Re: print binary

        Kapteyn's Star wrote, On 20/06/08 05:49:
        hi group,
        i try to compile code below but my compiler is failing. it tells:-
        printbin.c: In function ‘main’:
        printbin.c:9: error: invalid operands to binary & i am not able to
        understand what it mean. how to correct fault? please help i'm only new to
        C.
        >
        #include<stdio. h>
        #include<math.h >
        Since we moved away from punched cards spaces have been cheap. Using a
        few more will make your code a lot more readable.

        #include <stdio.h>
        #include <math.h>
        main()
        Implicit int (which you use above) is gone from the latest C standard.
        Not many compilers support the latest C standard fully, but why break
        compatibility just to save a very small amount of typing? Also better to
        be eplicit about no parameters.

        int main(void)
        {
        int val,npow;
        printf("enter value:");
        There is no guarantee that the above will be printed immediately due to
        line buffering. You should flush stdout here.
        scanf("%d",&val );
        scanf is generally a poor choice of function for user input. Better to
        use fgets and then pass the entered line possibly using sscanf. Whatever
        you use you should check the value returned by the input function.
        for(npow=31;npo w>-1;--npow){
        int could be either more or less than 32 bits.
        if(val&pow(2,np ow))putchar(1);
        Lets space the above out so it is actually possible to read it.
        if (val & pow(2,npow)) putchar(1);

        OK, the "&" above is the only one on the line so it must be something to
        do with that. Look up "&" in your text book and you will find it works
        on integer types only. Loop up pow and you will find it returns a double
        (i.e. something other than an integer type).

        Actually, you should look at using the shift operator instead of using pow.
        else putchar(0);
        }
        }
        --
        Flash Gordon

        Comment

        • Kapteyn's Star

          #5
          Re: print binary

          In a47c7c19-0b5b-47f8-9245-2d28df19bc56...le groups.com,
          Robert Gamble (Thu, 19 Jun 2008 22:19:23 -0700):
          On Jun 20, 12:49 am, Kapteyn's Star <inva...@invali d.invalidwrote:
          >hi group,
          >i try to compile code below but my compiler is failing. it tells:-
          >printbin.c: In function ‘main’:
          >printbin.c:9 : error: invalid operands to binary & i am not able to
          >understand what it mean. how to correct fault? please help i'm only new
          >to C.
          >>
          >#include<stdio .h>
          >#include<math. h>
          >main()
          >{
          >    int val,npow;
          >    printf("enter value:");
          >    scanf("%d",&val );
          >    for(npow=31;npo w>-1;--npow){
          >        if(val&pow(2,np ow))putchar(1);
          >        else putchar(0);
          >    }
          >>
          >}
          >>
          >>
          >>
          The pow() function returns a double value, the binary & operator works
          only with integer operators. You can cast the return value of pow() to
          int, or use a more efficient method to do your bit checking. Your
          putchar calls should be changed to putchar('1') and putchar('0')
          respectively, putchar(1) will print the character with the numeric value
          of 1 as opposed to the character that represents the number 1. You
          should also print a newline at the end out your output. You should have
          a correct prototype for main() and a little more liberal use of
          whitespace would be welcome. Here is a revised version:
          >
          #include <stdio.h>
          #include <math.h>
          >
          int main(void)
          {
          int val, npow;
          >
          printf("enter value: ");
          scanf("%d", &val);
          >
          for (npow = 31; npow -1; --npow) {
          (val & (int) pow(2, npow)) ? putchar('1') : putchar('0');
          }
          putchar('\n');
          >
          return 0;
          }
          >
          Like the original, this assumes a 32-bit int and the multiple calls to
          pow() are very inefficient. Instead of "val & (int) pow(2, npow)" try
          "val & 1<<npow".
          thanks a lot! but i don't understand one thing. the program gives the
          same bits for input = 2^31 and 2^31-1. only the correct value for 2^31 is
          printed for -2^31. can any one explain why?

          again thanks very much.

          Comment

          • Kapteyn's Star

            #6
            Re: print binary

            In t9tri5x3fh.ln2@ news.flash-gordon.me.uk, Flash Gordon (Fri, 20 Jun 2008
            06:54:35 +0100):

            In t9tri5x3fh.ln2@ news.flash-gordon.me.uk, Flash Gordon (Fri, 20 Jun 2008
            06:54:35 +0100):
            Kapteyn's Star wrote, On 20/06/08 05:49:
            >hi group,
            >i try to compile code below but my compiler is failing. it tells:-
            >printbin.c: In function ‘main’:
            >printbin.c:9 : error: invalid operands to binary & i am not able to
            >understand what it mean. how to correct fault? please help i'm only new
            >to C.
            >>
            >#include<stdio .h>
            >#include<math. h>
            >
            Since we moved away from punched cards spaces have been cheap. Using a
            few more will make your code a lot more readable.
            >
            #include <stdio.h>
            #include <math.h>
            >
            >main()
            >
            Implicit int (which you use above) is gone from the latest C standard.
            Not many compilers support the latest C standard fully, but why break
            compatibility just to save a very small amount of typing? Also better to
            be eplicit about no parameters.
            >
            int main(void)
            okay. my textbook actually uses "int main()" but i wrote main to save
            space. is int main() better or int main(void) is better? what is the
            differance between them?
            >{
            > int val,npow;
            > printf("enter value:");
            >
            There is no guarantee that the above will be printed immediately due to
            line buffering. You should flush stdout here.
            >
            > scanf("%d",&val );
            >
            scanf is generally a poor choice of function for user input. Better to
            use fgets and then pass the entered line possibly using sscanf. Whatever
            you use you should check the value returned by the input function.
            >
            > for(npow=31;npo w>-1;--npow){
            >
            int could be either more or less than 32 bits.
            my book mentions int is 4 bytes. If it is less or more then what should I
            do. I should look at sizeof(int) and set npow to 15 if it return 2 and 63
            if it return 8?
            > if(val&pow(2,np ow))putchar(1);
            >
            Lets space the above out so it is actually possible to read it.
            if (val & pow(2,npow)) putchar(1);
            >
            OK, the "&" above is the only one on the line so it must be something to
            do with that. Look up "&" in your text book and you will find it works
            on integer types only. Loop up pow and you will find it returns a double
            (i.e. something other than an integer type).
            Sorry. i read about it and forgot. I will cast pow to int.
            Actually, you should look at using the shift operator instead of using
            pow.
            Okay, i'm not yet at shift ops but i will write a shifted version.
            > else putchar(0);
            > }
            >}
            thanks for all your advice.

            Comment

            • Joachim Schmitz

              #7
              Re: print binary

              Kapteyn's Star wrote:
              In t9tri5x3fh.ln2@ news.flash-gordon.me.uk, Flash Gordon (Fri, 20 Jun
              2008 06:54:35 +0100):
              >
              In t9tri5x3fh.ln2@ news.flash-gordon.me.uk, Flash Gordon (Fri, 20 Jun
              2008 06:54:35 +0100):
              >
              >>main()
              >>
              >Implicit int (which you use above) is gone from the latest C
              >standard. Not many compilers support the latest C standard fully,
              >but why break compatibility just to save a very small amount of
              >typing? Also better to be eplicit about no parameters.
              >>
              >int main(void)
              >
              okay. my textbook actually uses "int main()" but i wrote main to save
              space. is int main() better or int main(void) is better? what is the
              differance between them?
              int main() is required by the latest standard which dropped the implicit
              int.
              int main(void) is better as it tells the compiler as well as the human
              reader that there won't be any arguments
              >>{
              >> int val,npow;
              >> printf("enter value:");
              >>
              >There is no guarantee that the above will be printed immediately due
              >to line buffering. You should flush stdout here.
              >>
              >> scanf("%d",&val );
              >>
              >scanf is generally a poor choice of function for user input. Better
              >to use fgets and then pass the entered line possibly using sscanf.
              >Whatever you use you should check the value returned by the input
              >function.
              >>
              >> for(npow=31;npo w>-1;--npow){
              >>
              >int could be either more or less than 32 bits.
              >
              my book mentions int is 4 bytes. If it is less or more then what
              Then your book is wrong or tied to a certain implementation.
              should I do. I should look at sizeof(int) and set npow to 15 if it
              return 2 and 63 if it return 8?
              to be on the safe sideuse

              #include <limits.h>
              sizeof(int) * CHAR_BIT - 1

              Bye, Jojo


              Comment

              • Kapteyn's Star

                #8
                Re: print binary

                In g3fcs1$b64$1@ai oe.org, Kapteyn's Star (Fri, 20 Jun 2008 06:49:05
                +0200):

                After following what every one has adviced i wrote the code below. i
                tested it for many values and binary conversion is ok but strtoul seems
                to give wrong answers. where could be the problem? i have copied out a
                session here.

                ../printbin 0
                You entered: 0 (hex: 0).
                binary: 000000000000000 000000000000000 00

                ../printbin 1
                You entered: 0 (hex: 0).
                binary: 000000000000000 000000000000000 01

                ../printbin 10
                You entered: 0 (hex: 0).
                binary: 000000000000000 000000000000010 10

                ../printbin 0xffffffff
                You entered: 4294967040 (hex: ffffff00).
                binary: 111111111111111 111111111111111 11

                ../printbin 0xfffffff0
                You entered: 4294967040 (hex: ffffff00).
                binary: 111111111111111 111111111111100 00

                #include <limits.h>
                #include <stdlib.h>
                #include <stdio.h>
                void ui2bstr(unsigne d long val, char *buf) {
                int bitpos;
                for(bitpos=size of(unsigned long)*CHAR_BIT-1; bitpos >= 0; bitpos--) {
                if(val & (1UL << bitpos)) {
                buf[(sizeof(unsigne d long)*CHAR_BIT-1)-bitpos] = '1';
                }
                else {
                buf[(sizeof(unsigne d long)*CHAR_BIT-1)-bitpos] = '0';
                }
                }
                buf[sizeof(unsigned long)*CHAR_BIT] = '\0';
                }
                int main(int argc, char *argv[]) {
                unsigned long num=strtoul(arg v[1], NULL, 0);
                char buf[sizeof(unsigned long)*CHAR_BIT];

                ui2bstr(num,buf );
                printf("You entered: %lu (hex: %lx).\nbinary: %s\n",num,num,b uf);
                }

                Comment

                • Kapteyn's Star

                  #9
                  Re: print binary

                  In g3fon3$ljd$1@ai oe.org, Kapteyn's Star (Fri, 20 Jun 2008 10:11:15
                  +0200):

                  very sorry for not saying before my compiler is gcc(4.1.0) and glibc
                  (2.3.6).

                  Comment

                  • CBFalconer

                    #10
                    Re: print binary

                    Flash Gordon wrote:
                    Kapteyn's Star wrote:
                    >
                    .... snip ...
                    >
                    > scanf("%d",&val );
                    >
                    scanf is generally a poor choice of function for user input.
                    Better to use fgets and then pass the entered line possibly
                    using sscanf. Whatever you use you should check the value
                    returned by the input function.
                    Actually scanf is a quite safe way to input single (emphasize
                    single) numeric values interactively, as long as you check its
                    return value.

                    if (1 != scanf("%d, &val)) {
                    /* failure, do something about it */
                    }
                    else {
                    /* success, you can use val */
                    /* but remember there is unused data in the stdin line */
                    }

                    --
                    [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

                    • Antoninus Twink

                      #11
                      Re: print binary

                      On 20 Jun 2008 at 6:22, Kapteyn's Star wrote:
                      thanks a lot! but i don't understand one thing. the program gives the
                      same bits for input = 2^31 and 2^31-1. only the correct value for 2^31 is
                      printed for -2^31. can any one explain why?
                      Integers in C are stored using the 2s complement system. This means that
                      the most signficant bit is a sign bit: it's 1 for negative numbers and 0
                      for non-negative numbers. On your system, an int is 32 bits, which means
                      that you can store numbers from (-2^31) to (2^31 - 1) inclusive.

                      The bit pattern of 2^31 is a 1 in the sign bit, followed by zeros. In
                      the 2s complement system, this represents the largest negative number,
                      namely -2^31.

                      If you change val to be an unsigned int rather than an int (and change
                      the scanf format specifier to %u), then you'll be able to deal with
                      numbers between 0 and (2^32-1) inclusive.

                      By the way, using pow() is a /really/ bad way to calculate small powers
                      of 2: follow the suggestion elsewhere in the thread and use (1<<npow)
                      instead. This is likely to translate to a single instruction in the
                      compiled machine code.

                      Comment

                      • Bartc

                        #12
                        Re: print binary


                        "Kapteyn's Star" <remove_digits_ for_email_7Kapt eyns3.Star@g0m8 ai2l.9com>
                        wrote in message news:g3fon3$ljd $1@aioe.org...
                        In g3fcs1$b64$1@ai oe.org, Kapteyn's Star (Fri, 20 Jun 2008 06:49:05
                        +0200):
                        >
                        After following what every one has adviced i wrote the code below. i
                        tested it for many values and binary conversion is ok but strtoul seems
                        to give wrong answers. where could be the problem? i have copied out a
                        session here.
                        #include <limits.h>
                        #include <stdlib.h>
                        #include <stdio.h>
                        void ui2bstr(unsigne d long val, char *buf) {
                        int bitpos;
                        for(bitpos=size of(unsigned long)*CHAR_BIT-1; bitpos >= 0; bitpos--) {
                        if(val & (1UL << bitpos)) {
                        buf[(sizeof(unsigne d long)*CHAR_BIT-1)-bitpos] = '1';
                        }
                        else {
                        buf[(sizeof(unsigne d long)*CHAR_BIT-1)-bitpos] = '0';
                        }
                        }
                        buf[sizeof(unsigned long)*CHAR_BIT] = '\0';
                        }
                        int main(int argc, char *argv[]) {
                        unsigned long num=strtoul(arg v[1], NULL, 0);
                        This crashes for me when no arguments are given. Check that argc is at least
                        2.
                        char buf[sizeof(unsigned long)*CHAR_BIT];
                        For 32 bits for example you will need 33 characters to allow for the
                        terminator. So an extra char is needed.

                        BTW (unsigned long)*CHAR_BIT is a little unwieldly to keep writing (5 times
                        above); perhaps put into a macro.
                        >
                        ui2bstr(num,buf );
                        printf("You entered: %lu (hex: %lx).\nbinary: %s\n",num,num,b uf);
                        }
                        --
                        Bartc


                        Comment

                        • Joachim Schmitz

                          #13
                          Re: print binary

                          Antoninus Twink wrote:
                          On 20 Jun 2008 at 6:22, Kapteyn's Star wrote:
                          >thanks a lot! but i don't understand one thing. the program gives the
                          >same bits for input = 2^31 and 2^31-1. only the correct value for
                          >2^31 is printed for -2^31. can any one explain why?
                          >
                          Integers in C are stored using the 2s complement system.
                          Wrong, they are at best likely to be stored in 2s complement, but 1s
                          compelent is also possible. All depends on the implementation

                          Bye, Jojo


                          Comment

                          • Kapteyn's Star

                            #14
                            Re: print binary

                            In xoK6k.12623$E41 .9530@text.news .virginmedia.co m, Bartc (Fri, 20 Jun 2008
                            09:04:29 +0000):

                            Thanks Bartc, making buf to 33 chars fixed the problem! i also did as you
                            said and created a marco as follows:-

                            #define UL_BITS (sizeof(unsigne d long)*CHAR_BIT)

                            everything seems ok now. thanks to everyone.

                            Comment

                            • Kapteyn's Star

                              #15
                              Re: print binary

                              In slrng5msaj.5pl. nospam@nospam.i nvalid, Antoninus Twink (Fri, 20 Jun 2008
                              08:58:59 +0000):

                              In slrng5msaj.5pl. nospam@nospam.i nvalid, Antoninus Twink (Fri, 20 Jun 2008
                              08:58:59 +0000):
                              On 20 Jun 2008 at 6:22, Kapteyn's Star wrote:
                              >thanks a lot! but i don't understand one thing. the program gives the
                              >same bits for input = 2^31 and 2^31-1. only the correct value for 2^31
                              >is printed for -2^31. can any one explain why?
                              >
                              Integers in C are stored using the 2s complement system. This means that
                              the most signficant bit is a sign bit: it's 1 for negative numbers and 0
                              for non-negative numbers. On your system, an int is 32 bits, which means
                              that you can store numbers from (-2^31) to (2^31 - 1) inclusive.
                              >
                              The bit pattern of 2^31 is a 1 in the sign bit, followed by zeros. In
                              the 2s complement system, this represents the largest negative number,
                              namely -2^31.
                              I think i'm getting it. all bit pattern with top most bit is 0 are
                              positive values and 0 and those wih top bit of 1 are negative values. is
                              this ok? i find the scheme where top bit is sign bit to be simpler to
                              understand.
                              If you change val to be an unsigned int rather than an int (and change
                              the scanf format specifier to %u), then you'll be able to deal with
                              numbers between 0 and (2^32-1) inclusive.
                              >
                              By the way, using pow() is a /really/ bad way to calculate small powers
                              of 2: follow the suggestion elsewhere in the thread and use (1<<npow)
                              instead. This is likely to translate to a single instruction in the
                              compiled machine code.
                              i have included another version with these improvments in another post.

                              thanks for the info!

                              Comment

                              Working...