LoginSignup
1

[C++] 10進数数値を2進数文字列に変換する(2パターン)

Last updated at Posted at 2023-05-14

タイトルにある通り、整数型の数値を2進数表記(文字列)に変換する方法を2つご紹介する。

1. bitset

bitset についてはこちら。

conv_bitset.cpp
#include <iostream>
#include <bitset>
using namespace std;

int main(void){
    cout << "数値を入力してください:";
	long long n;
	cin >> n;

	bitset<60> bs(n);
	cout << bs << endl;
}
# コンパイル
$ g++ conv_bitset.cpp

#実行(数値として 123456789 を入力)
$ ./a.out
数値を入力してください:123456789
000000000000000000000000000000000111010110111100110100010101

2. format

format についてはこちら。

conv.format.cpp
#include <iostream>
#include <format>
using namespace std;

int main(void){
    cout << "数値を入力してください:";
	long long n;
	cin >> n;

	string s = format("{:0>60b}", n);// 60桁の2進数表記で、'0'で左詰めする
	cout << s << endl;
# コンパイル
$ g++ conv_format.cpp

#実行(数値として 123456789 を入力)
$ ./a.out
数値を入力してください:123456789
000000000000000000000000000000000111010110111100110100010101

format は C++20 から導入された、新しい機能である

コンパイル時、fatal error: format: No such file or directory のようなエラーが出たら、お使いの環境が C++20 より古い可能性がある。

以下で導入方法を簡単に説明する。

前提

  • M1 Mac
  • C++ コンパイラ: g++

format が利用可能な g++ バージョン確認

こちらのページ にて、GCC libstdc++ の列、 Text formatting の行のところを見ると、13 となっている。

image.png

マシンの g++ バージョン確認

$ g++ --version
#g++ (Homebrew GCC 11.x.x) 11.x.x (x の部分は忘れました)

g++ 13 のインストール

$ brew install gcc@13
$ g++ --version
#Apple clang version 14.0.0 (clang-1400.0.29.202)
#Target: arm64-apple-darwin21.6.0
#Thread model: posix
#InstalledDir: /Library/Developer/CommandLineTools/usr/bin

コンパイラが Clang に設定されてしまった。
Mac では、デフォルトの g++ コンパイラが Clang らしい?ので、g++ をコンパイラとして設定しなくてはならない。
このバージョンアップ以前にも g++ を使用していたが、その際にも設定は行っていたが、どうやら g++ のバージョンを上げたことでデフォルトしてしまったらしい。

g++ をコンパイラとして設定するには、シンボリックリンクを該当のフォルダへ貼る。

$ ln -s /opt/homebrew/bin/g++-13 /usr/local/bin/g++

M1 Mac での homebrew

$ g++ --version
#g++ (Homebrew GCC 13.1.0) 13.1.0
#Copyright (C) 2023 Free Software Foundation, Inc.
#This is free software; see the source for copying conditions.  There is NO
#warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$which g++
#/usr/local/bin/g++

無事 g++ 13 がインストールされた。

コンパイル

$ g++ conv_format.cpp
# ...error: 'format' was not declared in this scope

このエラーはコンパイル時に C++20 であることを伝えることで解消される。

$ g++ -std=c++20 conv_format.cpp

#実行(数値として 123456789 を入力)
$ ./a.out
数値を入力してください:123456789
000000000000000000000000000000000111010110111100110100010101

bitset の場合と同様の出力結果となった。

まとめ

bitset でも format でも一度設定すればコード量も変わらないが、format はさまざまなフォーマティングに対応しているので、みて見ると面白いかもしれない。

:book: 参考にさせていただいた記事

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1