bin2dec

This is a discussion on bin2dec within the C Programming forums, part of the General Programming Boards category; I am writing a program for opengl that converts a file of 0 and 1 to the hex format. If ...

  1. #1
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926

    bin2dec

    I am writing a program for opengl that converts a file of 0 and 1 to the hex format. If you know about opengl it is going to be for stippled polygons. I am going to convert them to integers first, then hex. Here is what I have. I don't have a compile to check. but is this an efficient way of doing this? and will it work?
    Code:
    #include <stdio.h>
    
    int bin2dec(char *dec);
    
    int main(void){
    	FILE *infile;
    	int retval;
    	char buffer[8]={0}; /*0-7 + '\0'*/
    	infile=fopen(argv[1],"rb");
    	while(fread(buffer,sizeof buffer,1,infile)!=NULL){
    		retval=bin2dec(buffer);
    	/*rest of code*/
             }
    	return 0;
    }
    
    int bin2dec(char *dec){
    	int x=0, temp,total=0;
    	while(dec[x]!='\0' || dec[x]!='\n'){
    		if(dec[x]=='1'){
    			temp=pow(x,2);
    			total+=temp;
    			x++;
    		}
    		if(dec[x]=='0'){
    			continue;
    		}
    	}
    }
    [EDIT]This is for my own use and I will assume I wrote the file in a square that is a multiple of 8[/EDIT]
    Last edited by linuxdude; 03-22-2004 at 01:06 PM.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Why not strtol?
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
       const char binary[] = "11001";
       int decimal = strtol(binary, NULL, 2);
       printf("binary = \"%s\", decimal = %d = 0x%02X\n",
              binary, decimal, decimal);
       return 0;
    }
    
    /* my output
    binary = "11001", decimal = 25 = 0x19
    */
    [edit]Found my crayons and added color.
    Last edited by Dave_Sinkula; 03-22-2004 at 04:40 PM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21