bitsetを使用してバイナリと10進数の相互変換を実現
2486 ワード
一、相互変換
注意bitset bs(num);の中のSizeは定数でなければならないので、先頭0に行くのは面倒です.
しかし、悲劇的にはbit setは32ビットの符号なし整数しか受信できないので、自分で書く必要があります.
二、0~2^kのバイナリ数を生成する
先頭ゼロなし:
先頭ゼロ:
PS:いい問題
注意bitset bs(num);の中のSizeは定数でなければならないので、先頭0に行くのは面倒です.
#include
#include
#include
#include
#include
#include
using namespace std;
const int Size = 32;
char str[Size];
int main(void)
{
int num;
while (~scanf("%d", &num)) /// !
{
/// 2
bitset 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('
');
/// 1
string str2(str);
bitset<32> bs2(str2);
printf("%d
", bs2.to_ulong()); /// %lud
/// 2,#include
printf("%d
", strtol(str, NULL, 2)); /// %ld
}
return 0;
}
しかし、悲劇的にはbit setは32ビットの符号なし整数しか受信できないので、自分で書く必要があります.
#include
#include
#include
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
#include
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
#include
#include
using namespace std;
const int Size = 4;
const int maxn = 1 << Size;
int main(void)
{
for (int i = 0; i < maxn; ++i)
{
bitset bs(i);
puts(bs.to_string().c_str());
}
return 0;
}
PS:いい問題