I am new to C and for an assignment I have to print the 8-bit binary representation of a combination of up to 5 ASCII characters ie. D3% = 01000100 00110011 00100101.
Here is my code:
void ascii_to_binary(int * option_stats, char * ascii)
{
int i, j, num_value, count, binary[40], length, space=0; /* binary array length of 40 as */
length = strlen(ascii); /* 5*8 bit characters is 40 */
count = 8;
pos = 0
printf("Binary representation: ");
for (i = 0; i < length; i++)
{
num_value = ascii[i];
while(count > 0)
{
if((num_value%2) == 0)
{
binary[pos] = 0;
num_value = num_value/2;
count--;
pos++;
}
else
{
binary[pos] = 1;
num_value = num_value/2;
count--;
pos++;
}
}
count = 8; /*resets loop counter*/
}
for(j = pos-1; j >= 0; j--)
{
printf("%d", binary[j]);
space++;
if(space == 8)
{
printf(" "); /*white space between bytes*/
}
}
read_rest_of_line(); /*used as part of the larger program as a whole,
please ignore*/
}
The ASCII characters I have entered are passed from a separate function, the code is below:
void run_ascii_binary(void)
{
char input[MAX_STRING_INPUT + EXTRA_SPACES], ascii;
int option_stats;
printf("ASCII to Binary Generator\n");
printf("-------------------------\n");
printf("Enter a String (1-5 characters): ");
if (fgets(input, MAX_STRING_INPUT+EXTRA_SPACES, stdin) != NULL)
{
sscanf(input, "%s", &ascii);
}
ascii_to_binary(&option_stats, &ascii);
}
My issue is when it comes to printing the actual binary.
The output I get is: 00100101 11001100 01000100 in which the 1st byte and 3rd byte are in the wrong order. Any tips to get it to print it in the correct order would be great!
thanks!