私は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 で、1 番目のバイトと 3 番目のバイトの順序が間違っています。正しい順序で印刷するためのヒントは素晴らしいでしょう!
ありがとう!