jalilweb.com

You are here: Home arrow University arrow Programming
  • Decrease font size
  • Default font size
  • Increase font size
Programming
how to calculate the number of bits in an integer Print E-mail
Written by Jalil   
Tuesday, 02 June 2009

if you want to know the number of bits constituting an integer look no further. Here is a very simple solution.

int get_number_of_bits(int the_number){
           int bits = 1;
           int div = (the_number/2);
           while(div != 0){
                      bits++;
                      div = div/2;
           }
           return bits;
}

 

So this is just a simple division by 2 loop, that counts the number of times we could divide the number by two without the result being less than 1 (which is the number of bits -1).

This works for positive integers from 0 and up.

 

Now if you wanted to know the number of bits required to represent a number of elements (i.e. you want to know how many bits would represent a number of states, elements or anything you like)

then use the same algorithm above, except that you need to change the line:  int div = the_number/2   into int div = (the_number-1)/2

this is because, number of states or elements is never 0.

 

Feedback is very welcome.

 

 

Last Updated ( Tuesday, 02 June 2009 )
 
STLPLUS: open source extension of c++ standard template library Print E-mail
Written by Jalil   
Saturday, 15 March 2008

If you ever needed a C++ library that extends on the standard template library and provides more advanced containers, then STLplus is probably your best bet. STLplus is a project developped by Andrew Rushton over many many years which provides some of the most used data structures like: Directed Graphs, N-ary Trees...etc. It is also portable between Windows and Linux. The creator of this library has used it for the development of the Moods Behavioural Synthesis tool at the university of Southampton.

Last Updated ( Saturday, 22 March 2008 )
Read more...
 
C++: Save Console Output to a File Print E-mail
Written by Jalil   
Thursday, 13 March 2008
The most annoying thing when developing console applications (especially under windows) is when you cannot see the entire output when it is too long for the command line window to handle.

The only way around this is to print the output to a file that you can later open and read. You can usually do this by instantiating an output stream and write to it. But there is a simpler and tidier way to achieve that.

Include this line in your Main function:

std::freopen("output.txt", "w", stdout);

What this function does is that it redirects the standard output stream "cout" to the file you specify in its first argument.

Simple, Tidy and Useful.

Last Updated ( Monday, 14 April 2008 )