I have written a function in c to convert a base-10 number into its binary representation with 16 bits. A space should also appear in the output of this function, E.G.: 00000000 00000001 = 1. The conversion itself works correctly, but I'm having trouble getting this value back to the main as a string. I don't get any errors, but upon printing sequence_number (one character at a time), I get ASCII symbols. I realize that this is common question, but I have read many similar posts and cannot identify what I have done wrong.
void convertToBinary(char *ReturnV, int _this){
//Declare Variables
int bin_no[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, bin_Index;
int working = _this;
int i, c, singleDigit, a;
char working_Return[19];
char binaryDigit[1];
for(bin_Index = 15; bin_Index > 0; bin_Index--) {//Conversion
working = (working/2);
bin_no[bin_Index] = working%2;
}
for(i = 0; i < 17; i++) {//Convert to string
singleDigit = bin_no[i];
sprintf(binaryDigit, "%d", singleDigit);
working_Return[i] = binaryDigit[0];
}
for(a = 17; a > 9; a--) {//Insert space
//Copy all values over
working_Return[a+1] = working_Return[a];
}
working_Return[9] = ' ';//Insert Space
strcpy(ReturnV, working_Return);
}
My function is called using
int sequenceNumber_Lower = 48;
char sequence_number[19];
convertToBinary(sequence_number, sequenceNumber_Lower);
but when I attempt to print the values from sequence_number (from main) using
for(c=0 ; c<18 ; c++) {
printf("%c", sequence_number[c]);
}
I get random ascii symbols. I've verified that the working_Return string holds the correct values so the error must lie in copying the values at the end of the function. Or have I done this incorrectly and I am trying to print what has been deleted?
I'm aware that when the function ends, the local variables are destroyed, but I feel that I've done this correctly as I've looked at many posts on here and other sites that say this is one of the valid ways of returning a string from a function. Can you help me see what I've done wrong?
I've tried returning a pointer to this string with the function declaration (and according definition)
char * convertToBinary(int _this);
But this had the same results.
Your code has two main problems:
You use sprintf in an string with only one char, but sprintf always puts an '\0' after the last char printed, so it would overwrite memory outside your string. This is called buffer overrun.
Another problem in your code is that in C all strings passed to printf MUST end with '\0'. It is the marker of "End of String" used by default in C. If your string does not have one, the printf function will continue printing whatever is in memory until it find one.
So declaring
and in the end adding:
will solve your problems.
The changes proposed on other answers are valid as well. For example:
is much faster than sprintf. Writing directly to the buffer is also much faster.