plz explain

This is a discussion on plz explain within the C++ Programming forums, part of the General Programming Boards category; can sum1 explain exactly how this program calculates the number of bits required to store a number(i got it off ...

  1. #1
    I'll take you down! polonyman's Avatar
    Join Date
    Sep 2004
    Posts
    50

    plz explain

    can sum1 explain exactly how this program calculates the number of bits required to store a number(i got it off a tutorial and its aint explainin)
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        int bitsRequired = 1; 
        int largest = 1; 
        int powerOf2 = 2;
        int number;
    
        cout << "Enter a positive integer: ";
        cin >> number;
    
        while (number > largest)
        {
            bitsRequired += 1;
            powerOf2 = powerOf2 * 2;
            largest = powerOf2 - 1;
        }
    
        cout << "To store " << number << " requires ";
        cout << bitsRequired << " bits" << endl;
        
        cin.ignore();
        cin.get();
    
        return 0;
    }
    thankz in advance

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    Well all powers of 2 in binary just have ONE bit set - eg 00100000

    A power of 2 minus 1 clears that bit, and sets all the bits to the right to 1, so
    00100000 would be 00011111

    The loop stops when a largest value is greater than the number you want to represent
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. plz explain the output of the program.
    By raj_ksrt in forum C++ Programming
    Replies: 2
    Last Post: 05-26-2008, 03:43 AM
  2. Plz explain difference between functions returning ref
    By dudeomanodude in forum C++ Programming
    Replies: 8
    Last Post: 05-08-2008, 01:03 PM
  3. plz explain a small function
    By samirself in forum C Programming
    Replies: 4
    Last Post: 11-11-2004, 09:14 AM
  4. Can someone explain this to me plz...
    By CAP in forum C Programming
    Replies: 3
    Last Post: 07-23-2002, 01:30 PM
  5. Replies: 1
    Last Post: 05-07-2002, 04:18 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21