質問

私はオペレーティングシステムに関する大学のコースをフォローしていますが、バイナリからヘキサデシマル、10進数から16進数などに変換する方法を学んでいます。今日、2つの補数を使用して署名/符号なしの数値がメモリに保存される方法を学びました+ 1)。

紙の上でやるべきエクササイズがいくつかあります。教師に仕事を提出する前に、回答を確認できるようにしたいと思います。最初のいくつかの演習のためにC ++プログラムを書きましたが、今では、次の問題で答えをどのように確認できるかについてこだわっています。

char a, b;

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

b = a >> 3;

そして、バイナリ表現を示す必要があります メモリでa, bc.

私は紙でそれをやったが、それは私に次の結果を与えてくれます(2人の補完の後に数字を記憶しているすべてのバイナリ表現):

a = 00111010(それはcharですので、1バイト)

b = 00001000(それはcharですので、1バイト)

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

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

役に立ちましたか?

解決

最も簡単な方法は、おそらく作成することです 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';

他のヒント

オンザフライ変換を使用します std::bitset. 。一時的な変数、ループ、関数、マクロなし。

コリルに住んでいます

#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

整数だけでなく、オブジェクトのビット表現を表示したい場合は、最初にチャーアレイとして再解釈することを忘れないでください。次に、その配列の内容を、ヘックスとして、またはバイナリとして(ビットセットを介して)印刷できます。

#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);
}

最も一般的なシステムは小さなエンディアンであるため、の出力は show_binrep(c)いいえ あなたが期待する1111111 011000101は、それがメモリに保存される方法ではないためです。あなたが探しているなら 価値 バイナリの表現、その後単純 cout << bitset<16>(c) 作品。

C ++には、数値を記憶してバイナリ表現を示す標準的な方法はありますか?

いいえ std::bin, 、 お気に入り std::hex また std::dec, 、しかし、自分で数のバイナリを出力するのは難しくありません:

他のすべてをマスキングすることで左のビットを出力し、左シフトを繰り返し、持っているすべてのビットに対してそれを繰り返します。

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

すでに投稿されているものと同様に、ビットシフトとマスクを使用してビットを取得します。あらゆるタイプで使用可能で、テンプレートです(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);
    }
}

再利用可能な機能:

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);
}

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

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

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

template<typename T>
string toBinary(const T& t)
{
  string s = "";
  int n = sizeof(T)*8;
  for(int i=n; 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 = ã => 111000110
b = ° => 111111000
c = -315 => 11111111011000101

数字のバイナリ表現を取得する真の方法は次のとおりです。

unsigned int i = *(unsigned int*) &x;

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

std::cout << std::hex << val << std::endl;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top