为什么只有以下两个函数之一打印出正确的转换:文本文件到 16 位和 8 位显示?

Why does only one of the two following functions print the correct conversion: text-file to 16 and 8-bit displays?

为什么我的程序主函数中只有以下两个函数之一打印文本文件(其中只有单个字符 '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;.

鉴于我们对 *value 的理解是 char,并且 displayMask 的二进制值为 0b10000000 00000000 00000000 00000000,以下看起来很可疑:

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

8 似乎是一个神奇的数字。也许你的意思是 CHAR_BIT?您可以从 <limits.h> header.

中包含 UCHAR_MAXCHAR_BIT

printf( "%10u = ", *value ); 稍微不那么挑剔,但为了安全起见,将 *value 转换为 unsigned int 可能是个好主意。