-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecimal_binary_conversion.cpp
More file actions
39 lines (30 loc) · 907 Bytes
/
Copy pathdecimal_binary_conversion.cpp
File metadata and controls
39 lines (30 loc) · 907 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
- Convert an integer to its binary representation -
std::bitset has a .to_string() method that returns a std::string holding a text
representation in binary, with leading-zero padding.
*/
#include <iostream>
#include <bitset>
#include <string>
using std::cout;
using std::string;
int main()
{
// test with an 8-bit value
unsigned int x = 255;
// to binary
string binary = std::bitset<8>(x).to_string();
cout << binary << '\n';
// back to decimal
unsigned long decimal = std::bitset<8>(binary).to_ulong();
cout << decimal << '\n';
///////////////////////////////////////////////////////////
// test with a 16-bit value
unsigned long y = 512;
// to binary
binary = std::bitset<16>(y).to_string();
cout << binary << '\n';
// back to decimal
decimal = std::bitset<16>(binary).to_ulong();
cout << decimal << '\n';
}