20131109【C言語】共用体を使う
お題
共用体を使う
プログラム概要
共用体の整数メンバに値を代入して、
char型のメンバを入れ替えることで暗号化を行い出力する。
その後、復号化して出力する。
ソース
#include <stdio.h>
int encode(int i);
int main(void)
{
int i;
i = encode(10);/* Encrypt */
printf("Encrypted 10 is %d.\n", i);
i = encode(i);/* Decode */
printf("Decode i is %d.\n",i);
return 0;
}
/* Encode integer and decode encoded integer */
int encode (int i)
{
union crypt_type {
int num;
char c[2];
} crypt;
unsigned char ch;
crypt.num = i;
/* Exchage 2 bytes */
ch = crypt.c[0];
crypt.c[0] = crypt.c[1];
crypt.c[1] = ch;
/* Return encrypted integer */
return crypt.num;
}
実行結果
Encrypted 10 is 2560.
Decode i is 10.