0

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

ありがとう!

4

2 に答える 2

2

asciichar5と aに十分な大きさである必要があります\0

char ascii[5+1];
...
sscanf(input, "%5s", &ascii);

初期化するoption_stats

int option_stats = 0;

コメントを外しlength = strlen(ascii);ます。前の行の未終了コメントによってコメントアウトされています。

OPが正確に8回ループする必要があるという@LtWorfは正しいです。

// while(num_value > 0) {
int bit;
int counti = count;  /// see below
for (i=8; i-- > 0; ) {

さらに、ビットは重要度の低いものから大きなものへと累積されますが、それらを最大のものから最小のものへと表示したいと考えています。したがって、それらを逆の順序で文字列に蓄積します。

// In two places
// binary[count] = ...
binary[counti] = ...

コードをクリーンアップする方法は他にもありますが、これらは 5 つの主な問題です。

于 2013-09-16T01:47:13.733 に答える
1
while(num_value > 0)

これは間違っています。char は負になることもあります。代わりに 8 回繰り返したほうがよいでしょう。

于 2013-09-15T23:37:34.600 に答える