繁体   English   中英

模板类型转换成二进制表示形式

[英]template type into binary representation

#include <iostream>

using namespace std;

template<class T>
void toBinary(T num) 
{
  char *  numi = reinterpret_cast<char*>(&num);

  for (int i = 1; i <= sizeof(T); i++)  
  {
      for( int j = 1 ; j <= 8; ++j )
      {
          char byte = numi[i];
          cout << ( byte & j  ? 1 :  0);    
      }
  }
  cout << endl << endl;
}

int main() 
{   
  toBinary(1); 
  std::cin.get();
}

输出为0000000000000 ...您能告诉我我的错误在哪里吗?

编辑:

#include <iostream>
#include <bitset>
#include <iomanip>
#include <boost/format.hpp>
using namespace std;

template<class T> bitset<sizeof(T)*CHAR_BIT> toBinary(const T num) 
{
    bitset<sizeof(T)*CHAR_BIT> mybits;
    const char * const p = reinterpret_cast<const char*>(&num);
    for (int i = sizeof(T)*CHAR_BIT-1 ; i >= 0 ; --i)
        mybits.set(i, (*(p)&(1<<i)));
    return mybits;
}

template<class T> void printBinary(T num, ostream& stream = cout)
{
    stream << boost::format("%-35s %-8s %-32s\n")  %  typeid(T).name() % num % toBinary(num).to_string();
}

struct Foo{void bar(){}};

int main() 
{   
  printBinary(-8);
  printBinary(8u);
  printBinary('a');
  printBinary(8.2f);  
  printBinary("Overflow");
  printBinary(main);
  printBinary(&Foo::bar);
  printBinary(8.2);
  std::cin.get();
}

我看到两件事:

  1. 循环i应该从0开始
  2. j++应该是j <<= 1

确实,

1      = 0b00000001
1 << 1 = 0b00000010
1 << 2 = 0b00000100
...

将此与您的工作进行对比:

1     = 0b00000001
1 + 1 = 0b00000010
1 + 2 = 0b00000011
1 + 3 = 0b00000100

这不是你想要的。

同样,该标准也不保证一个字节中有8位。 保证char类型为一个字节, sizeof以字节为单位测量大小,并且要知道字节中的位数,请使用CHAR_BIT宏:

for (j = 1; j <= 1 << CHAR_BIT; j <<= 1)
{
    char byte = numi[i];
    cout << (byte & j ? 1 : 0);    
}  

byte & j不检查是否设置了第j个位,它仅检查j中设置的任何位是否也设置为byte

要检查特定的位,请使用(byte & (1 << j)) != 0 (在这种情况下,j从零开始!)。

我想, 如果我真的想按原样修复此代码,我会这样做:

#include <iostream>
#include <string>

using namespace std;

template<class T>
    void toBinary(const T& num) 
{
  const char *const  asbytes = reinterpret_cast<const char* const>(&num);

  for (const char* byte=asbytes + sizeof(T) - 1; byte>=asbytes; byte--)
  {
      for ( int bitnr = 7; bitnr>=0; bitnr-- )
      {
          cout << ( (*byte & (1<<bitnr))  ? 1 :  0);    
      }
  }
  cout << endl << endl;
}

int main() 
{   
  toBinary(1); 
  std::cin.get();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM