One, mutual conversion
#include <cstdio>
#include <cmath>
#include <cstring>
#include < cstdlib>
#include <string>
#include <bitset>
07.using namespace std;
08.const int Size =;
10.char str[size];
12.int Main (void)
13.{ int num;
While (~scanf ("%d", &num))///prevents negative values from being entered!
. { ///into unsigned 2
-in-system. bitset<size> BS (num);
strcpy ( str, bs.to_string (). C_STR ()); ///Note Log to add 1e-9
. for (int i = size-(int) log2 (num + 1e-9)-1; i < size; ++i)
. Putchar (Str[i]); Putchar (' \ n ');
. Change back Method 1
. String str2 (str); bitset<32> BS2 (str2); printf ("%d\n", Bs2.to_ulong ());///or write%lud
. ///changed back to Method 2, #include <cstdlib>
. printf ("%d\n", Strtol (str, NULL, 2)); or write%ld
. }
return 0;
34.}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Second, the generation of 0~2^k binary number
No leading 0:
#include <cstdio>
#include <string>
03.using namespace std;
04.const int MAXN = 1 << 7;
06.string BS;
08.int Main (void)
09.{ int i, II; ///no leading 0
. for (i = 0; i < MAXN ++i)
. { Ii. II = i; bs = "";
. { bs = (ii & 1?) "1": "0") + BS;
>>=- II 1;
. while (ii); puts (BS.C_STR ());
. return 0;
25.}
Has a leading 0:
#include <cstdio>
#include <string>
#include <bitset>
04.using namespace std ;
05.const int Size = 4;
06.const int MAXN = 1 << Size;
08.int Main (void)
09.{
for (int i = 0; i < MAXN ++i) one
. { bitset<size> BS (i);
Puts ( bs.to_string () c_str ());
. return 0;
16.}