-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconvert integer to binary string and vice versa.cpp
More file actions
70 lines (58 loc) · 1.24 KB
/
convert integer to binary string and vice versa.cpp
File metadata and controls
70 lines (58 loc) · 1.24 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<bits/stdc++.h>
using namespace std;
#define int long long
string removeZeroesfromfront(string s)
{
int j=0;
while(s[j]=='0')
j++;
string ans = s.substr(j,s.size()-j);
if(ans.size()==0)
ans="0";
return ans;
}
string intoBinString(int x)
{
string s;
// will give a 64 bit string
for(int i = 63; i >= 0; i--)
s += (x >> i & 1) + '0';
// removing zeroes from front
s = removeZeroesfromfront(s);
return s;
}
// note int means long long here
// for LC, change int to ll
int binStringtodec(string s)
{
int val=0;
for(auto &it:s)
val = val * 2 + (it - '0');
return val;
}
// to find remainder of string x when divided by x -
/*
int binStringtodec(string s,int x)
{
int val=0;
for(auto &it:s)
{
val = val * 2 + (it - '0');
val = val%x;
}
return val;
}
*/
int32_t main()
{
// std::string binary = std::bitset<32>(1000000000).to_string(); //to binary--> this will give string of size 32.
// // this conversion will work fine till 1e9 .. abouve that number use bitset<64>
// std::cout<<binary<<"\n";
//
// unsigned long decimal = std::bitset<32>(binary).to_ulong();
// int dec= decimal;
// std::cout<<dec<<"\n";
string s = "1000";
cout << binStringtodec(s) << endl;
cout << intoBinString(0) << endl;
}