![](/img/trans.png)
[英]How to assign only 16 bits to any integer in a binary file instead of the normal 32 in C++?
[英]c++ bit operations how to print out 16, 32 bits
目前我有腳本將數值打印成比特,例如
print((short) 1);
我得到一個00000001
的值,但我怎么能得到像00000001 00000000
這樣的值以及如果我打印print((int) 1);
我得到的值為00000001 00000000 00000000 00000000
。 這是我的代碼:
void printbyte(unsigned char x)
{
for (int i = 0; i < 8; i++)
{
if (x & 0x80) cout << 1;
else cout << 0;
x = x << 1;
}
cout << endl;
}
template <typename T>
void print (T A)
{
unsigned char *p = (unsigned char *) &A;
printbyte(*p);
}
int main()
{
print((short) 1);
system("pause");
return 0;
}
您可以在print
使用sizeof(T)
來確定要處理的字節數,然后為每個字節調用printbyte
,例如
#include <iostream>
#include <climits>
using namespace std;
void printbyte(unsigned char x)
{
for (int i = 0; i < CHAR_BIT; i++)
{
cout << ((x & 0x80) != 0);
x <<= 1;
}
}
template <typename T>
void print (T A)
{
for (size_t i = 0; i < sizeof(T); ++i)
{
unsigned char b = A >> ((sizeof(T) - i - 1) * CHAR_BIT);
//unsigned char b = A >> (i * CHAR_BIT); // use this for little endian output
printbyte(b);
cout << " ";
}
cout << endl;
}
int main()
{
print((short) 1);
print((long long) 42);
return 0;
}
你可以使用bitset,這是最簡單的方法。 這是一個例子:
#include <iostream>
#include <bitset>
using namespace std;
int main ()
{
int number;
cin>>number;
bitset <16> end (number);
cout<<number<<" --> "<<end<<'\n';
return 0;
}
或參考: http : //www.cplusplus.com/reference/bitset/bitset/
如果您不想使用標准解決方案,它也可能如下所示:
#include <iostream>
#include <climits>
using namespace std;
template <typename Type>
void bprint(Type in)
{
unsigned char* p = (reinterpret_cast<unsigned char*>(&in))+(sizeof(Type)-1); //x86
for(unsigned int n = sizeof(Type);n--;--p, std::cout<<' ')
for(unsigned int i = CHAR_BIT;i--;)
std::cout<<((*p&char(1<<i))!=0);
std::cout<<'\n';
}
int main(void)
{
int number;
cin>>number;
bprint(number);
bprint(short(number));
bprint(char(number));
return 0;
}
如果默認情況下未設置“char *”,則需要“unsigned”。 根據標准,訪問變量的內存只有變量類型或unsigned char的指針。
最有趣的選擇是使用數學,尤其是Gynvael Coldwind,這里描述: http : //gynvael.coldwind.pl/n/c_cpp_number_to_binary_string_01011010 。
我認為你應該使用std :: bitset ,但是你總是必須在編譯時指定大小。 為避免這種情況,您可以使用這樣的模板函數(請注意,這是C ++ 11):
#include <iostream>
#include <bitset>
#include <limits>
template <class T> void PrintBits (const T &Number) {
std::bitset<std::numeric_limits<T>::digits> Bit_Number(Number);
std::cout << Bit_Number << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.