/*Here's my first go at creating a int-to-binary convert using templates for an array class. My goal is to create a display to show how bitwise operations affect binary numbers.
I solved it, but I harvested (read found/stole) the bitwise code, and I'm not exactly sure how.why it works, though it is very intelligent code in my opinion. I will mark the stolen code and the source below;
(0.3 has a few corrections to put the binary print out in the right order) */
/* I have updated the code with an explanation as to how the bitwise evaluation works, now that I understand it myself. I also tightened up the code in the actual assignment, removing the if statement and replacing it with a direction evalution (x&1)/assignment.*/
#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T>
class array{
T* val;
int _leng;
public:
array(int l):_leng(l){
val=new T[_leng];
};
~array(){
delete[] val;
};
T& operator[](int index){
return val[index];
};
int leng(){return _leng;}
void disp(){
for(int i=_leng;i>=0;i--){
cout<<(*this)[i];
}
};
};
// toBits operates as thus: k is the value of val right-shifted by c. With fir this c begins as 8
// and val is 15(or 1111bin). Since a right shift of 8 places pushes the values clear, k==0. When
// k is compared to bin value of one(1bin), this results in a false, so 0 is assigned to fir[8].
// Next c==7, bit shifting right 7 places. This is still too far, so the same assignment happens.
// So it goes until c==3. Once we shift the value only 3 places, the comparison (& operator) evals
// to true, so fir[3] is assigned 1. This repeats until c==0, when k==true and the loop is complete.
// Thus, the fir.disp() feedback 00001111.
// Now lets look at sec: 16(or 10011bin) runs to c==4. Here, when the number is shifted
// k==1, and is assigned to fir. When it is shifted by 3 places, we can see (if we pick the number
// in binary expression) the value is 0, and assigned as such.
void toBits(array<bool>fir,int val){
for (int c = fir.leng(); c >= 0; c--){
// Everything from here to...
int k,n;
k = val >> c;
fir[c]=k&1;//except this
// ...here all comes from this source: http://www.programmingsimplified.com/c/source-code/c-program-convert-decimal-to-binary, save for some minor modifications to fit the code.
}
fir.disp();
}
int main(){
array<bool>fir(8);
toBits(fir,4);
int en=0;
cin>>en;
return 0;
}
No comments:
Post a Comment