Print binary numbers from 0 to M. Size N bits. Ascend

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • elieli
    New Member
    • Apr 2014
    • 3

    Print binary numbers from 0 to M. Size N bits. Ascend

    Hello,
    I need help writing a program that print binary numbers from 0 to M.
    Size N bits.
    Ascending or descending order according to user choice.
    When the default is M = 8, N = 3

    Thank you
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    All numbers are binary in the computer. Do you mean you want to take a value like 5 and print 101?

    Comment

    • elieli
      New Member
      • Apr 2014
      • 3

      #3
      no,
      insert in the begining a value to M,N. (define M 8, define N 3).

      and then the program need to print the all binar numbers from 0 to M in N bytes by order.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        So if M is 8 and N is 3, what do you expect to print?

        Comment

        • elieli
          New Member
          • Apr 2014
          • 3

          #5
          000
          001
          010
          011
          100
          101
          110
          111

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            So you are printing 101 for a value of 5.

            You can use this algorithm to get the binary value from the integer value:

            4/1 4 4%2 0
            4/2 2 2%2 0
            4/4 1 1%2 1

            5/1 1 5%2 1
            5/2 2 2%2 0
            5/4 1 1%2 1


            6/1 6 1%2 0
            6/2 3 3%2 1
            6/4 1 1%2 1


            7/1 7 7%2 1
            7/2 3 3%2 1
            7/4 1 1%2 1

            As you can see, to get the binary digit at a position you divide your value by the binary value at that position. The result will be odd or even. Then you use the % operator to see odd or even as 1 or 0.

            Comment

            Working...