Decimal to binary conversion

Hi
i have used showbits function to convert decimal to binary.showbit(7) gives 000000000000111.can i directly store this value in an array and then how to acess the individual elements.

Regards
vinoth
You can use the bitset class and use its [ ] operator to access the single bits:
http://www.cplusplus.com/reference/stl/bitset/
i would appreciate if you can explain it with an example for my case.
1
2
3
4
5
6
7
8
//   #include <bitset>
// assume '16' to be the number of bits you want
bitset<16> bs = 7;
cout << "7 in binary is : " << bs.to_string() // to_string returns an std::string with the binary digits ( 000...0111 )
     << ", its 4th bit is " << bs[3]; // bs[3] shows the 4th  ( 000...0111 ) 
bs [3] = 1; // it can be used to change the bit value ( 000...1111 )
cout <<"\nIf it 4th bit was 1, the result would be: " << bs.to_string() << " ( " 
    << bs.to_ulong() << " in decimal )"; // to_ulong returns the number corresponding to the binary data 
Last edited on
Topic archived. No new replies allowed.