简体   繁体   English

如何在c中打印文件的二进制代码?

[英]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?所以我想在 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);

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:将文件转储为 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演示: 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.

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