Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

binUtils.C

Go to the documentation of this file.
00001 
00009 #include <vector>
00010 #include <cassert>
00011 #include "binUtils.h"
00012 
00013 namespace binOp {
00014 
00015   unsigned int fastLog2(unsigned int num) {
00016     if(num) {
00017       return (binLength(num) - 1);
00018     } else {
00019       assert(false);
00020       return -1;
00021     }
00022   }//end function
00023 
00024   unsigned int binLength(unsigned int num) {
00025     unsigned int len = 1;
00026     while(num > 1) {
00027       num = (num >> 1);
00028       len++;
00029     }
00030     return len;
00031   }//end function
00032 
00033   int toBin(unsigned int num, unsigned int binLen,  std::vector<bool>& numBin) {
00034     numBin = std::vector<bool>(binLen);
00035     for(unsigned int i = 0; i < binLen; i++) {
00036       numBin[i]=0;
00037     }//end for
00038     unsigned int pos = binLen -1;
00039     while(num > 0) {
00040       numBin[pos] = (num%2);
00041       num = num/2;  
00042       pos--;
00043     }  //end while  
00044     return 1;
00045   }//end function
00046 
00047   unsigned int binToDec(unsigned int* numBin, unsigned int binLen) {
00048     unsigned int res = 0;
00049     for(unsigned int i = 0; i< binLen; i++) {
00050       res = (2*res) + numBin[i];
00051     }
00052     return res;
00053   }//end function
00054 
00055 
00056   bool isPowerOfTwo(unsigned int n) {
00057     return (n && (!(n & (n - 1))));
00058   }
00059 
00060   // compute the next highest power of 2 of 32-bit v
00061   int getNextHighestPowerOfTwo(unsigned int n) {
00062     unsigned int v = n;
00063     assert(v > 0);
00064     v--;
00065     v |= (v >> 1);
00066     v |= (v >> 2);
00067     v |= (v >> 4);
00068     v |= (v >> 8);
00069     v |= (v >> 16);
00070     v++;
00071     return v;
00072   }
00073 
00074   // compute the prev highest power of 2 of 32-bit v
00075   int getPrevHighestPowerOfTwo(unsigned int n) {
00076     unsigned int v = n;
00077     assert(v > 0);
00078     v--;
00079     v |= (v >> 1);
00080     v |= (v >> 2);
00081     v |= (v >> 4);
00082     v |= (v >> 8);
00083     v |= (v >> 16);
00084     v++;
00085     return  (v >> 1);
00086   }
00087 
00088 }//end namespace
00089 

Generated on Tue Mar 24 16:14:04 2009 for DENDRO by  doxygen 1.3.9.1