how to reverse the output in c++

edited July 2005 in Internet & Media
hi!
there is a c++ programe to convert a decimal number into binary.i have somehow done it but the output is in reverse order.that is if we take input 4 then the answers should be 100 but it gives 001.plz guide me what to do?

Comments

  • mmonninmmonnin Centreville, VA
    edited July 2005
    Again, code please.
  • shwaipshwaip bluffin' with my muffin Icrontian
    edited July 2005
    if the input is an int:
    void printInt(int toPrint){
      int x = 0x8000;
      for(int i=0; i<32; i++){
        if( (x & toPrint) == 0)
          cout << "0";
        else
          cout << "1";
        x = x >> 1;
      }
    }
    

    This masks off all the individual bits, and tests if' the result is zero. If it is, that bit is a zero.
  • edited July 2005
    mmonnin wrote:
    Again, code please.
    <
    main()
    {
    int n,r;
    cout<<"enter the integer";
    cin>>n;
    while(n>=1)
    {
    r = n % 2;
    n = n/2;
    cout<<r;
    }
    }
    >
    this is the code,with which i have tried to solve the problem but...
  • edited July 2005
    shwaip wrote:
    if the input is an int:
    void printInt(int toPrint){
      int x = 0x8000;
      for(int i=0; i<32; i++){
        if( (x & toPrint) == 0)
          cout << "0";
        else
          cout << "1";
        x = x >> 1;
      }
    }
    

    This masks off all the individual bits, and tests if' the result is zero. If it is, that bit is a zero.

    Be carefull of the big-endian/little-endian difference on machines. You might get;

    000000000000001000000000000000000

    when you want

    00000000000000000000000000000100
  • shwaipshwaip bluffin' with my muffin Icrontian
    edited July 2005
    cswett - yeah, there are a couple problems with the code I posted, including little/big endian assumptions and and size of int assumptions.

    sarah - The only way I can think of to solve the code using the way that you're working on it is to store the values in a temporary string, and then print it after you're done.
  • edited July 2005
    mmonnin wrote:
    Again, code please.
    <
    main()
    {
    int n,r;
    cout<<"enter the integer";
    cin>>n;
    while(n>=1)
    {
    r = n % 2;
    n = n/2;
    cout<<"r;
    }
    }
    >
  • shwaipshwaip bluffin' with my muffin Icrontian
    edited July 2005
    if you put the code in [php]
    code here
    
    [/php] tags, it'll keep your indents.
Sign In or Register to comment.