[英]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();
}
我看到兩件事:
i
應該從0
開始 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.