现在的位置: 首页 > 综合 > 正文

使用bitset实现二进制和十进制的相互转换

2018年05月02日 ⁄ 综合 ⁄ 共 1587字 ⁄ 字号 评论关闭

一、相互转换

注意由于bitset<Size> bs(num);中的Size必须为常数,所以去前导0比较麻烦。

#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<string>
#include<bitset>
using namespace std;
const int Size = 32;

char str[Size];

int main(void)
{
	int num;
	while (~scanf("%d", &num)) ///禁止输入负值!
	{
	    ///化成无符号2进制
		bitset<Size> bs(num);
		strcpy(str, bs.to_string().c_str());
		///注意算log要加上1e-9
		for (int i = Size - (int)log2(num + 1e-9) - 1; i < Size; ++i)
			putchar(str[i]);
		putchar('\n');

        ///变回来方法1
        string str2(str);
		bitset<32> bs2(str2);
		printf("%d\n", bs2.to_ulong()); ///或者写%lud

		///变回来方法2,#include<cstdlib>
		printf("%d\n", strtol(str, NULL, 2)); ///或者写%ld
	}
	return 0;
}

但悲剧的是bitset只能接收32位的无符号整数,所以我们需要自己写一个:

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
typedef unsigned long long ull;
const int mx = 65;

char bits[mx], tmp[mx];

void getBitsWithPreZero(ull n, int len)
{
	int i = 0;
	while (n)
	{
		tmp[i++] = '0' + (n & 1ULL);
		n >>= 1ULL;
	}
	memset(bits, '0', sizeof(bits));
	for (int j = len - i; j < len; ++j) bits[j] = tmp[--i];
	bits[len] = 0;
}

void getBitsWithoutPreZero(ull n)
{
	int i = 0, j = 0;
	while (n)
	{
		tmp[i++] = '0' + (n & 1ULL);
		n >>= 1ULL;
	}
	while (i) bits[j++] = tmp[--i];
	bits[j] = 0;
}

int main()
{
	ull n;
	int len;
	while (cin >> n >> len)
	{
		getBitsWithPreZero(n, len);
		puts(bits);
		getBitsWithoutPreZero(n);
		puts(bits);
	}
	return 0;
}

二、生成0~2^k的二进制数

无前导零:

#include<cstdio>
#include<string>
using namespace std;
const int maxn = 1 << 7;

string bs;

int main(void)
{
	int i, ii;
	///无前导零
	for (i = 0; i < maxn; ++i)
	{
		ii = i;
		bs = "";
		do
		{
			bs = (ii & 1 ? "1" : "0") + bs;
			ii >>= 1;
		}
		while (ii);
		puts(bs.c_str());
	}
	return 0;
}

有前导零:

#include<cstdio>
#include<string>
#include<bitset>
using namespace std;
const int Size = 4;
const int maxn = 1 << Size;

int main(void)
{
	for (int i = 0; i < maxn; ++i)
	{
		bitset<Size> bs(i);
		puts(bs.to_string().c_str());
	}
	return 0;
}

抱歉!评论已关闭.