Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Created April 18, 2018 15:05
Show Gist options
  • Save lovasoa/f6745bde7f838969d7a64aeda1dc6c02 to your computer and use it in GitHub Desktop.
Save lovasoa/f6745bde7f838969d7a64aeda1dc6c02 to your computer and use it in GitHub Desktop.
Read and write numbers in base 2
#include<iostream>
using namespace std;
unsigned int read_base2() {
int n=0; char c;
for(cin.get(c); c=='0'||c=='1'; cin.get(c)) n = (n<<1)|(c-'0');
return n;
}
void write_base2(unsigned int n, bool first=true) {
if (n==0 && first) cout << '0';
if (n==0) return;
write_base2(n>>1, false);
cout << (n&1);
}
int main() {
unsigned int n1 = read_base2();
unsigned int n2 = read_base2();
cout << n1 << " + " << n2 << " = " << n1+n2 << endl;
write_base2(n1+n2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment