Hello,
I have a string of binary number and I want to convert it into decimal and then output to a file in hexadecimal format as follow:
The output from the printf statement is trivial, but somehow the output to the file is 0xFE39. It's obviously not correct...
I'm thinking there is something not right about the int return type, but even it's the error i don't really know how to fix this. I'm fairly new to C language. Would someone please help?
I have a string of binary number and I want to convert it into decimal and then output to a file in hexadecimal format as follow:
int main(){ str = "1001110001111111"; oFilePtr = fopen(outFile,"w"); test = bin2dec(str); printf("%s\n",str); fprintf(oFilePtr,"0x%0.4X\n",test); //I was told to use this format for output to file, it gives me a warning btw return 0; } int bin2dec(char* binStr) { int decimalval = 0; int stringpos; for (stringpos=strlen(binStr)-1; stringpos>=0; stringpos--) { decimalval = decimalval<<1; if (binStr[stringpos]=='1') decimalval += 1; } return decimalval; }
The output from the printf statement is trivial, but somehow the output to the file is 0xFE39. It's obviously not correct...
I'm thinking there is something not right about the int return type, but even it's the error i don't really know how to fix this. I'm fairly new to C language. Would someone please help?