我是 C 新手,对于一项作业,我必须打印最多 5 个 ASCII 字符组合的 8 位二进制表示,即。D3% = 01000100 00110011 00100101。
这是我的代码:
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*/
}
我输入的 ASCII 字符是从一个单独的函数传递的,代码如下:
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);
}
我的问题是在打印实际的二进制文件时。
我得到的输出是: 00100101 11001100 01000100 其中第一个字节和第三个字节的顺序错误。任何让它以正确的顺序打印的提示都会很棒!
谢谢!