为什么我的程序主函数中只有以下两个函数之一打印文本文件(其中仅包含单个字符“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
?您可以包括 UCHAR_MAX
和CHAR_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/