char array gives inappropriate and unworthy output. Here I was making a binary converter everything is well but the output like this
'a ■wô▀╓vè▄╨ 0000 0000 0000 0101'
Don't know why but I just want simply '0000 0000 0000 0101'. Can you tell me where I'm wrong?
int number = 5;
int temp_num, remain, quotient;
char result[40];
// *Pointers
char *result_ptr = result;
int output_size = 16;
temp_num = number;
for (int i = 0; i < output_size; i++)
{
remain = temp_num % 2;
quotient = temp_num / 2;
if(remain == 0){*result_ptr++ = '\x30';}
else if(remain == 1){*result_ptr++ = '\x31';}
if((i + 1) % 4 == 0){*result_ptr++ = '\x20';} // separate every 4 bits
temp_num = quotient;
}
strrev(result);
puts(result);
return 0;
Your string is not terminated by
'\0'. As a result,strrevseems to do funny things, it reverses too long string (or whatever, this is likely to be undefined behavior due to buffer overflow).Simplest fix is to initialize your string to all zeroes:
The buffer length 40 is just big enough even for 32 bit integer, I think, 32 bits, 7 spaces and final 0 to terminate the string. However, you might want to add
assertor something to make sure you don't have buffer overflow.