20131107【C言語】ビットフィールドを使う

お題

ビットフィールドを使う

 

プログラム概要

スペースシャトルの機体情報を構造体で宣言し、各情報をビットフィールドとする。

各ビットフィールドにランダムな値(0 or 1)を格納することを3回実施する。

実施の度に、各ビットフィールドに基づく情報を表示しつつファイルに書き込む

 

ソース

#include <stdio.h>

#include <stdlib.h>

 

/* Case of 1: All of the files is normal

 * Case of 0: Out of order or fuel */

struct telemetry {

unsigned fuel: 1;

unsigned radio: 1;

unsigned tv: 1;

unsigned water: 1;

unsigned food: 1;

unsigned waste: 1;

} flt_recd;

 

void display(struct telemetry i);

 

int main(void)

{

FILE *fp;

int i;

 

if *1 == NULL) {

fprintf(stderr,"Cannot open file.\n");

exit(1);

}

 

/* Assuemed that per minute status report of space shuttle is recorded to disc file */

for (i = 0; i < 3; i++) {

flt_recd.fuel = rand() % 2;

flt_recd.radio = rand() %2;

flt_recd.tv = rand() % 2;

flt_recd.water = rand() % 2;

flt_recd.food = rand() % 2;

flt_recd.waste = rand() % 2;

 

display(flt_recd);

fwrite(&flt_recd, sizeof flt_recd, 1, fp);

}

 

fclose(fp);

 

return 0;

}

 

void display(struct telemetry i)

{

if (i.fuel)

printf("Fuel is normal.\n");

else

printf("Out of fuel.\n");

if (i.radio)

printf("Radio is normal.\n");

else

printf("Radio trouble.\n");

if (i.tv)

printf("TV is normal.\n");

else

printf("TV is out of order.\n");

if (i.water)

printf("Water supply is normal.\n");

else

printf("Water supply is shortage.\n");

if (i.food)

printf("Food supply is normal.\n");

else

printf("Food supply is shortage.\n");

if (i.waste)

printf("Waste storage is normal.\n");

else

printf("Cannot store waste.\n");

printf("\n");

}

 

実行結果

Fuel is normal.

Radio trouble.

TV is normal.

Water supply is normal.

Food supply is normal.

Waste storage is normal.

 

Out of fuel.

Radio trouble.

TV is normal.

Water supply is normal.

Food supply is shortage.

Waste storage is normal.

 

Out of fuel.

Radio is normal.

TV is normal.

Water supply is shortage.

Food supply is shortage.

Cannot store waste.

 

*1:fp = fopen("flight", "wb"