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 3 years have passed since last update.

文字列を2進数に変換してファイル出力する

Last updated at Posted at 2021-03-21

ASCIIコード表に基づいて最大8バイトの文字列を2進数(文字として出力)に変換する。
例)変換対象文字列がABCDEFGの場合
01000001,01000010,01000011,01000100,01000101,01000110, 01000111
に変換する。

int main(void)
{
	char filedata[8] = "ABCDEFG";	// 変換対象文字列
	char str[72]     = "";			// 変換後文字列
	int  storeNum    = 0;			// 格納位置
	int  bitCnt;					// 変換対象ビット
	int  byteCnt;					// 変換対象バイト
	char tmpBitChar;				// 変換後ビット一時格納先
	
	// 8文字分ループ(変換対象が終端ではない間)
	// && filedata[byteCnt]が無い場合は、文字のないバイトは0で出力される
	for (int byteCnt = 0; byteCnt < 8 && filedata[byteCnt]; byteCnt++) {
		// 8ビット分ループ
		for (int bitCnt = 8 - 1; bitCnt >= 0; bitCnt-- )
		{
			// 変換対象位置へシフトして1ビット分抜き出す
			tmpBitChar = filedata[byteCnt] >> bitCnt & 1;
			// 抜き出したビットを文字に変換(ASCII文字コードに対応)
			str[storeNum++] = tmpBitChar | '0';
		}
		// 8ビット区切りで[,]を入れる
		str[storeNum++] = ',';
	}
	// 末尾に終端文字格納
	str[storeNum - 1] = '\0';

	// ファイルオープン
	FILE *fp = fopen("./bitFile.txt", "w");
	// ファイルオープン確認
	if (!fp)
	{
		return 1;
	}
	// 文字列出力
	fprintf(fp, "%s\n", str);
	// ファイルクローズ
	fclose(fp);
}
0
1
1

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?