0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C言語の共用体について

Posted at
union_test.c
# include <stdio.h>

struct bits {
	unsigned char b1 : 1;
	unsigned char b2 : 1;
	unsigned char b3 : 1;
	unsigned char b4 : 1;
	unsigned char b5 : 1;
	unsigned char b6 : 1;
	unsigned char b7 : 1;
	unsigned char b8 : 1;
};

union test {
	unsigned char chr;
	struct bits bit;
};

int main()
{
	union test test;

    /* 共用体のサイズ */
	printf("sizeof(unoin) %luByte\n", sizeof(union test));

	test.chr = 10;
	printf("test.chr %d\n", test.chr);

	printf("bit\n");
	printf("0b %d%d%d%d%d%d%d%d\n",
		test.bit.b8, test.bit.b7, test.bit.b6, test.bit.b5,
		test.bit.b4, test.bit.b3, test.bit.b2, test.bit.b1);

	return 0;
}
実行結果
sizeof(unoin) 1Byte
test.chr 10
bit
0b00001010

共用体

構造体と似ているが(メンバアクセス方法など)大きな特徴として、メンバ変数でメモリを共用するということが挙げられます。
上例では"test"という共用体が定義されており、メンバとして"unsigned char"と"構造体bit"が定義されています。この2つのメンバがメモリを共用しているというわけです。メモリサイズはメンバの中で一番多くメモリを消費する変数のサイズとなっています。
実行結果を見てみると、変数chrに代入された10を構造体bitのメンバから参照することができています。

ビットフィールド

C言語では変数は"unsigned char"の8bitが最小単位ですが、ビットフィールドを使うと8bitよりも小さな変数(?)を作ることができます。注意が必要なのは構造体のメンバとしてのみ定義できるということです。

参考記事

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?