[英]How can I print the binary code of a file in c?
所以我想在 Windows 上做一個校驗和,但首先我需要得到一個包含二進制文件信息的字符串,但我的代碼只顯示其他格式的信息,誰能幫我得到這個只顯示 0 和1?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char linha[1024];
}linha;
int main() {
linha linha1;
char temp[1024];
FILE *arquivo;
if((arquivo = fopen("C:\\62-Q2.mp3","rb"))==NULL){
printf("Erro ao abrir o arquivo.");
exit(1);
}
fseek(arquivo, sizeof(linha), SEEK_SET);
while(!feof(arquivo)) {
fread(&linha1,sizeof(linha),1,arquivo);
strcpy(temp, linha1.linha);
printf("%u\n", temp);
}
fclose(arquivo);
return 0;
}
strcpy(temp, linha1.linha);
這行完全沒有意義,因為您不閱讀文本文件。
while(!feof(arquivo))
這總是錯誤的。
將文件轉儲為 bin 中的字節:
void printByteAsBin(unsigned char ch)
{
unsigned char mask = 1 << (CHAR_BIT - 1);
for(; mask; mask >>= 1) printf("%c", (ch & mask) ? '1' : '0');
}
void dumpBin(FILE *fi, int linelen)
{
int ch = fgetc(fi);
int linepos = 0;
char str[linelen + 1];
while(ch != EOF)
{
printByteAsBin(ch);
str[linepos] = (isalpha(ch) || ch == ' ') ? ch : '.';
if(++linepos < linelen) printf(" ");
else {str[linepos] = 0; printf(" %s\n", str); linepos = 0;}
ch = fgetc(fi);
}
if(ch == EOF && linepos != linelen )
{
for(int x = 0; x < (linelen - linepos) * 9; x++, printf(" "));
str[linepos] = 0;
printf("%s\n", str);
}
}
您應該添加一些錯誤和參數檢查。
演示: https : //godbolt.org/z/5nqeG3fE8
01001000 01100101 01101100 01101100 01101111 00100000 Hello
01010111 01101111 01110010 01101100 01100100 00001010 World.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.