c - 为什么以下两个函数中只有一个打印出正确的转换: text-file to 16 and 8-bit displays?

标签 c arrays prototype endianness

为什么我的程序主函数中只有以下两个函数之一打印文本文件(其中仅包含单个字符“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); , 毕竟。当我们讨论这一点时,明智的做法是转换 *valueunsigned char那里。

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

printf( "%10u = ", *value );稍微少一点,但为了安全起见,转换 *value 可能是个好主意到unsigned int那里。

关于c - 为什么以下两个函数中只有一个打印出正确的转换: text-file to 16 and 8-bit displays?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29202988/

相关文章:

c - 通过 union 别名

c++ - int_fast32_t 和 int_fast16_t 是 int 的类型定义。应该如何使用它?

java - 调用全局数组

javascript - 在JS中访问嵌套数组元素

c - 有没有办法保存和恢复C中的调用堆栈

C:如何递归地逐位传输字节?

php - 如何在不打断单词的情况下拆分长字符串?

Javascript 继承调用父级的非默认构造函数

javascript - 向原型(prototype)添加函数与对象字面量(使用 this)

JavaScript 原型(prototype)属性和原型(prototype)链接