简体   繁体   中英

How can I print the binary code of a file in c?

So I want to make a checksum on windows but first I need to get one string with the information of the file in binary but my code show only the information in other formats, can anyone help me get this to show this information only with 0 and 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);

this line makes no sense at all as you do not read text file.

while(!feof(arquivo)) 

This is always wrong.

To dump file as bytes in 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);
    }
}


You should add some error and parameter checking.

Demo: https://godbolt.org/z/5nqeG3fE8

01001000 01100101 01101100 01101100 01101111 00100000 Hello 
01010111 01101111 01110010 01101100 01100100 00001010 World.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM