How can i convert binary to decimal number or ascii in C
I have a file(pgm image) that contains ascii characters and binary
numbers(the binary part is not readable using text editor Notepad++.) It's
classified as P5 by GIMP P2 Portable graymap ASCII P5 Portable graymap
Binary I need do read the binary numbers and convert it to decimal
numbers. If i used fread i should get 0s and 1s, right?, but if i use
printf("%c",char_variable_name) i might be printing "Null" char and "Start
of Heading" char according to the ascii table, the first one i think is
printable but the second one isn't, so how can i use if(byte_px=='1' ||
byte_px=='0') and then print the char 1 or 0 on the screen?
int main(void){
unsigned char *byte_px=NULL; // cada byte representa 1 px
char ch;
int
cont=0,i,larg,alt,max_cinza,tam_arq,pos_fim_texto,intervalo_bin,qtd_elem_inter,busca_num,busca_qtd=0,qtd_0_1_bin;
FILE *arq;
arq = fopen("test.pgm","rb"); validacao_arq(arq);
while((ch=fgetc)!=EOF){
ch=fgetc(arq);
if(ch=='\n') cont++;
if(cont==2) break;
}
fscanf(arq,"%d %d %d ",&larg, &alt, &max_cinza);
pos_fim_texto=ftell(arq);
fseek(arq,0,SEEK_END);
tam_arq=ftell(arq);
qtd_0_1_bin = tam_arq-pos_fim_texto; // qtd_0_1_bin = the number of
bytes of the binary part of the file
printf("qtd_0_1_bin %d\n",qtd_0_1_bin);
qtd_elem_inter = max_cinza/intervalo_bin;
fseek(arq,pos_fim_texto,SEEK_SET);
byte_px = (unsigned char*) malloc((qtd_0_1_bin)*sizeof(unsigned char));
fread(byte_px,sizeof(unsigned char),qtd_0_1_bin,arq);
// THIS IS THE LINE I'D EXPECT TO PRINT 0s and 1s
for(i=0; i<qtd_0_1_bin; i++){
if(byte_px=='1' || byte_px=='0')
printf("%c",byte_px[i]);
}
fclose(arq);
return 0;
}
This is a similar example of a PGM file opened in Notepad++:
P5
# CREATOR: GIMP PNM Filter Version 1.1
20 20
255
ÿÿNULNULNULNULNULNULNULÿÿNULNULNULNULNULNULNULÿÿÿÿÿÿNULNULNULNULNULNULNULÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
No comments:
Post a Comment