272

私はオペレーティングシステムに関する大学のコースをフォローしており、2進数から16進数、10進数から16進数などに変換する方法を学んでいます。今日は、2の補数(〜number)を使用して符号付き/符号なしの数値がメモリに格納される方法を学びました。 + 1)。

紙で行う演習がいくつかあります。先生に作品を提出する前に、答えを確認できるようにしたいと思います。最初のいくつかの演習でC++プログラムを作成しましたが、次の問題で答えを確認する方法がわかりません。

char a, b;

short c;
a = -58;
c = -315;

b = a >> 3;

、、およびのメモリ内のバイナリ表現を表示する必要があります。abc

私はそれを紙で行いました、そしてそれは私に次の結果を与えます(2の補数の後の数の記憶にあるすべての2進表現):

a = 00111010(charなので、1バイト)

b = 00001000(charなので、1バイト)

c = 11111110 11000101(短いので、2バイト)

私の答えを確認する方法はありますか?C ++で数値のメモリにバイナリ表現を表示する標準的な方法はありますか、それとも各ステップを自分でコーディングする必要がありますか(2の補数を計算してからバイナリに変換する)?後者はそれほど長くはかからないだろうと私は知っていますが、そうするための標準的な方法があるかどうかについて興味があります。

4

12 に答える 12

517

最も簡単な方法は、おそらくstd::bitset値を表すものを作成し、それをにストリーミングすることcoutです。

#include <bitset>
...

char a = -58;
std::bitset<8> x(a);
std::cout << x << '\n';

short c = -315;
std::bitset<16> y(c);
std::cout << y << '\n';
于 2011-09-08T14:35:55.750 に答える
134

オンザフライ変換を使用してstd::bitset。一時変数、ループ、関数、マクロはありません。

Live On Coliru

#include <iostream>
#include <bitset>

int main() {
    int a = -58, b = a>>3, c = -315;

    std::cout << "a = " << std::bitset<8>(a)  << std::endl;
    std::cout << "b = " << std::bitset<8>(b)  << std::endl;
    std::cout << "c = " << std::bitset<16>(c) << std::endl;
}

プリント:

a = 11000110
b = 11111000
c = 1111111011000101
于 2013-03-17T07:39:35.657 に答える
37

std::formatC ++ 20では、これを行うために使用できるようになります。

unsigned char a = -58;
std::cout << std::format("{:b}", a);

出力:

11000110

それまでの間、に基づいて{fmt}ライブラリを使用できます。std::format{fmt}は、printこれをさらに簡単かつ効率的にする関数も提供します(godbolt)。

unsigned char a = -58;
fmt::print("{:b}", a);

免責事項:私は{fmt}とC++20の作者ですstd::format

于 2020-12-16T20:50:41.603 に答える
27

整数だけでなく、任意のオブジェクトのビット表現を表示する場合は、最初にchar配列として再解釈することを忘れないでください。次に、その配列の内容を16進数として、または(ビットセットを介して)2進数として出力できます。

#include <iostream>
#include <bitset>
#include <climits>

template<typename T>
void show_binrep(const T& a)
{
    const char* beg = reinterpret_cast<const char*>(&a);
    const char* end = beg + sizeof(a);
    while(beg != end)
        std::cout << std::bitset<CHAR_BIT>(*beg++) << ' ';
    std::cout << '\n';
}
int main()
{
    char a, b;
    short c;
    a = -58;
    c = -315;
    b = a >> 3;
    show_binrep(a);
    show_binrep(b);
    show_binrep(c);
    float f = 3.14;
    show_binrep(f);
}

ほとんどの一般的なシステムはリトルエンディアンであるため、の出力は期待する1111111 011000101でshow_binrep(c)ないことに注意してください。これは、メモリに格納される方法ではないためです。バイナリでの値の表現を探している場合は、簡単にcout << bitset<16>(c)機能します。

于 2011-09-08T14:40:53.620 に答える
13

数値のメモリ内のバイナリ表現を表示するC++の標準的な方法はありますか[...]?

いいえ。、、のstd::binようなものはstd::hexありstd::decませんが、数値の2進数を自分で出力するのは難しくありません。

他のすべてのビットをマスクして左シフトして左端のビットを出力し、それをすべてのビットに対して繰り返します。

(タイプのビット数はですsizeof(T) * CHAR_BIT。)

于 2011-09-08T14:35:35.953 に答える
6

すでに投稿されているものと同様に、ビットシフトとマスクを使用してビットを取得します。テンプレートであるため、どのタイプでも使用できます(1バイトのビット数を取得する標準的な方法があるかどうかはわかりませんが、ここでは8を使用しました)。

#include<iostream>
#include <climits>

template<typename T>
void printBin(const T& t){
    size_t nBytes=sizeof(T);
    char* rawPtr((char*)(&t));
    for(size_t byte=0; byte<nBytes; byte++){
        for(size_t bit=0; bit<CHAR_BIT; bit++){
            std::cout<<(((rawPtr[byte])>>bit)&1);
        }
    }
    std::cout<<std::endl;
};

int main(void){
    for(int i=0; i<50; i++){
        std::cout<<i<<": ";
        printBin(i);
    }
}
于 2011-09-08T14:45:41.923 に答える
4

再利用可能な機能:

template<typename T>
static std::string toBinaryString(const T& x)
{
    std::stringstream ss;
    ss << std::bitset<sizeof(T) * 8>(x);
    return ss.str();
}

使用法:

int main(){
  uint16_t x=8;
  std::cout << toBinaryString(x);
}

これは、あらゆる種類の整数で機能します。

于 2018-06-04T05:47:49.987 に答える
1
#include <iostream> 
#include <cmath>       // in order to use pow() function
using namespace std; 

string show_binary(unsigned int u, int num_of_bits);

int main() 
{ 

  cout << show_binary(128, 8) << endl;   // should print 10000000
  cout << show_binary(128, 5) << endl;   // should print 00000
  cout << show_binary(128, 10) << endl;  // should print 0010000000

  return 0; 
}

string show_binary(unsigned int u, int num_of_bits) 
{ 
  string a = "";

  int t = pow(2, num_of_bits);   // t is the max number that can be represented

  for(t; t>0; t = t/2)           // t iterates through powers of 2
      if(u >= t){                // check if u can be represented by current value of t
          u -= t;
          a += "1";               // if so, add a 1
      }
      else {
          a += "0";               // if not, add a 0
      }

  return a ;                     // returns string
}
于 2015-11-04T20:40:47.987 に答える
0

古いC++バージョンを使用すると、次のスニペットを使用できます。

template<typename T>
string toBinary(const T& t)
{
  string s = "";
  int n = sizeof(T)*8;
  for(int i=n-1; i>=0; i--)
  {
    s += (t & (1 << i))?"1":"0";
  }
  return s;
}

int main()
{
  char a, b;

  short c;
  a = -58;
  c = -315;

  b = a >> 3;

  cout << "a = " << a << " => " << toBinary(a) << endl;
  cout << "b = " << b << " => " << toBinary(b) << endl;
  cout << "c = " << c << " => " << toBinary(c) << endl;
}

a = => 11000110
b = => 11111000
c = -315 => 1111111011000101
于 2019-04-14T23:29:31.073 に答える
0

std :: bitset回答と便利なテンプレートの使用:

#include <iostream>
#include <bitset>
#include <climits>

template<typename T>
struct BinaryForm {
    BinaryForm(const T& v) : _bs(v) {}
    const std::bitset<sizeof(T)*CHAR_BIT> _bs;
};

template<typename T>
inline std::ostream& operator<<(std::ostream& os, const BinaryForm<T>& bf) {
    return os << bf._bs;
}

このように使用する:

auto c = 'A';
std::cout << "c: " << c << " binary: " << BinaryForm{c} << std::endl;
unsigned x = 1234;
std::cout << "x: " << x << " binary: " << BinaryForm{x} << std::endl;
int64_t z { -1024 };
std::cout << "z: " << z << " binary: " << BinaryForm{z} << std::endl;

出力を生成します:

c: A binary: 01000001
x: 1234 binary: 00000000000000000000010011010010
z: -1024 binary: 1111111111111111111111111111111111111111111111111111110000000000
于 2020-05-02T00:34:40.587 に答える
-5

数値の2進表現を取得する本当の方法は次のとおりです。

unsigned int i = *(unsigned int*) &x;
于 2015-10-19T15:33:49.087 に答える
-11

これはあなたが探しているものですか?

std::cout << std::hex << val << std::endl;
于 2011-09-08T14:33:50.787 に答える