为什么在我的程序主函数中,只有以下两个函数之一才能将文本文件(仅包含单个字符“ e”)正确转换为该字符“ e”的十六位和八位显示?例如,它仅打印:'e'= 101

101 = 01100101000000000 0000000000000000

0 = 00000000 00000000 00000000 00000000

它应显示为:
'e'= 101

101 = 01100101000000000 0000000000000000

101 = 01100101 00000000 00000000 00000000

#include<stdio.h>
#include<stdlib.h>

void displaySixteenBits(char *value );//prototype
void displayEightBits( char *value );//prototype


int main(void)
{
   FILE *ptr_file;
   char buf[1000];

   ptr_file = fopen("input.txt","r");

   if (!ptr_file)
      return 1;

   while (fgets(buf,1000, ptr_file)!=NULL)
      printf("The file read: \t");
   printf("%s\n",buf);
   /*Only one of the following two lines of code prints*/
   displaySixteenBits( buf );
   displayEightBits( buf );

   fclose(ptr_file);
   return 0;

}//end main



/* Function to display text file character to 16 bits*/
void displaySixteenBits( char *value )
{
   char c;

   int displayMask = 1 << 31;

   printf( "%10u = ", *value );

   for ( c = 1; c <= 32; ++c ) {

      putchar( *value & displayMask ? '1' : '0' );
      *value <<= 1;

      if (c % 16 == 0 ){
         putchar( ' ' );
      }
   }

   putchar( '\n' );
}//end display sixteen bits

/* Function to display text file character to eight bits*/
void displayEightBits( char *value )
{
   char c;

   int displayMask =  1 << 31;

   printf( "%10u = ", *value );

   for ( c = 1; c <= 32; ++c ) {

      putchar( *value & displayMask ? '1' : '0' );
      *value <<= 1;

      if (c % 8 == 0 ){
         putchar( ' ' );
      }

   }

   putchar( '\n' );
}//end display eight bits

最佳答案

int displayMask = 1 << 31;最多可能同时发生。在最坏的情况下,它根本无法完成您想做的事情。也许您的意思是unsigned long displayMask = 1UL << 31;

鉴于我们对*valuechar并且displayMask具有二进制值0b10000000 00000000 00000000 00000000的理解,以下内容看起来非常可疑:

*value & displayMask任何char的值大到足以需要32位的频率如何?毕竟,也许您的意思是unsigned char displayMask = ~(UCHAR_MAX >> 1);。当我们注意到这一点时,将*value强制转换为unsigned char可能是明智的。

8似乎是个魔术数字。也许您是说CHAR_BIT?您可以在UCHAR_MAX标头中包含CHAR_BIT<limits.h>

printf( "%10u = ", *value );不太松脆,但是为了安全起见,最好将*value强制转换为unsigned int

09-11 05:37