#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct {
bool b1:1;
bool b2:1;
unsigned char ch;
bool b3:1;
bool b4:1;
} st1;
typedef struct {
bool b1;
bool b2;
unsigned char c;
bool b3;
bool b4;
} st2;
void PrintBinary(unsigned char n )
{
for ( int i = 7; i >= 0; --i )
{
printf("%d", ( n >> i ) & 1);
}
}
void PrintBool(bool v)
{
printf( "%s ", v ? "true" : "false" );
}
int main()
{
st1 s1 = {0};
st2 s2 = {0};
unsigned char *p;
printf( "sizeof s1: %zu\n", sizeof s1 );
p = (unsigned char *)&s1;
printf("(A 1): ");
for ( unsigned int i = 0; i < sizeof s1; ++i )
{
PrintBinary( *(p + i) );
printf(" ");
}
printf("\n");
PrintBool( s1.b1 );
PrintBool( s1.b2 );
PrintBool( s1.b3 );
PrintBool( s1.b4 );
printf("\n");
s1.b2 = true;
printf("(A 2): ");
for ( unsigned int i = 0; i < sizeof s1; ++i )
{
PrintBinary( *(p + i) );
printf(" ");
}
printf("\n");
PrintBool( s1.b1 );
PrintBool( s1.b2 );
PrintBool( s1.b3 );
PrintBool( s1.b4 );
printf("\n");
s1.b3 = true;
printf("(A 3): ");
for ( unsigned int i = 0; i < sizeof s1; ++i )
{
PrintBinary( *(p + i) );
printf(" ");
}
printf("\n");
PrintBool( s1.b1 );
PrintBool( s1.b2 );
PrintBool( s1.b3 );
PrintBool( s1.b4 );
printf("\n");
printf( "sizeof s2: %zu\n", sizeof s2 );
p = (unsigned char *)&s2;
printf("(B 1): ");
for ( unsigned int i = 0; i < sizeof s2; ++i )
{
PrintBinary( *(p + i) );
printf(" ");
}
printf("\n");
PrintBool( s2.b1 );
PrintBool( s2.b2 );
PrintBool( s2.b3 );
PrintBool( s2.b4 );
printf("\n");
s2.b2 = true;
printf("(B 2): ");
for ( unsigned int i = 0; i < sizeof s2; ++i )
{
PrintBinary( *(p + i) );
printf(" ");
}
printf("\n");
PrintBool( s2.b1 );
PrintBool( s2.b2 );
PrintBool( s2.b3 );
PrintBool( s2.b4 );
printf("\n");
s2.b3 = true;
printf("(B 3): ");
for ( unsigned int i = 0; i < sizeof s2; ++i )
{
PrintBinary( *(p + i) );
printf(" ");
}
printf("\n");
PrintBool( s2.b1 );
PrintBool( s2.b2 );
PrintBool( s2.b3 );
PrintBool( s2.b4 );
printf("\n");
}
/*
output:
sizeof s1: 3
(A 1): 00000000 00000000 00000000
false false false false
(A 2): 00000010 00000000 00000000
false true false false
(A 3): 00000010 00000000 00000001
false true true false
sizeof s2: 5
(B 1): 00000000 00000000 00000000 00000000 00000000
false false false false
(B 2): 00000000 00000001 00000000 00000000 00000000
false true false false
(B 3): 00000000 00000001 00000000 00000001 00000000
false true true false
*/
Comments
0 B
|👍
/👎
0 B
|👍
/👎