# How to use Bitset to realize binary and decimal conversion

Source: Internet
Author: User

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

```#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.}```

```#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.}```
Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.