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;
CodePudding user response:
Your string is not terminated by '\0'
. As a result, strrev
seems 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:
char result[40] = "";
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 assert
or something to make sure you don't have buffer overflow.
CodePudding user response:
If you add the string terminator at output_size (output_size/4)-1 then you have the right output size to end as your output size only goes up to 16 which in your number (0000 0000 0000 0101) is 0 0000 0000 0101 (a string with the length of 16) so if you add the output_size / 4 then you should get the actual size of the output and because it is binary the output size should always be a multiple of 4 and if not you could always add an if statement to fix it. The -1 is to remove the extra character as for your number (0000 0000 0000 0101) output_size (output_size/4) is equal to 20 so you'd be assigning at the index of 20 so if you change it to -1 then you are accounting for the 0 index too.
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;
result[output_size (output_size/4)-1] = '\0';
}
puts(result);
strrev(result);
puts(result);
Hope it helps