这是我的代码:
#include <iostream>
//extract i:th bit from val of given addr with &
void extractBit(long long unsigned* ptr,int ith) {
std::cout << (*ptr & (1LLU << ith) ? 1 : 0);
}
template <typename T> void printlnbits(T v)
{
//v_size to hold the size of the generic variable
const int v_size = sizeof(v) * 8;
int j = 0;
unsigned long long int* ptr = reinterpret_cast<unsigned long long int*>(&v);
for (int n = v_size - 1; n >= 0; --n)
{
j++;
extractBit(ptr, n);
if (j == 8)
{
std::cout << " ";
j = 0;
}
}
std::cout << "\t" << v_size << std::endl;
}
struct foo {
int a = 2;
char b = -1;
unsigned long long int x = 1LLU << 63;
};
int main() {
const char a = 'a'; //97, displayed binary: 01100001, size:8bit
const foo b; /*displayed binary: 00000000 00000000 00000000 00000000 00000000 000000000 00000000 00000000 11001100 11001100 11001100 11111111 00000000 00000000 00000000 00000010
size: 128bit
*/
printlnbits(a);
printlnbits(b);
return 0;
}
char 'a' 的 ascii 值为 97,二进制表示为:01100001。char 的大小为 8 位。
结构值是我无法理解的。它的值为:14757395474574999554,或二进制:000000000000000000000000000000000000000000000000000000000000000000000000000000来方面000000000000000000000000000000000000000000000000000000000000000000000000000000000000来视
该结构的大小为 128 位。据我了解是这样存储的:
|----------------------------------------------|
| int a: 32bit | char b: 8bit | padding: 24bit-|
|----------------------------------------------|
|--------unsigned long long int x: 64bit-------|
|----------------------------------------------|
如您所见,该结构由一个非常奇数的二进制数表示。哪种方法用于以二进制形式存储给定变量的结构?我试图为它找到任何 IEEE 标准,但没有成功。