问题描述
我必须从标准输入中准确读取 4 个字节,然后将其视为小端字节序并将其显示在标准输出上,但我不知道我读取的内容是否正好是 4 个字节。我试过这个:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <byteswap.h>
int main() {
uint32_t f;
printf("Enter a value :");
scanf ("%" SCNu32,&f);
printf("Value of integer:%d",f);
//printf("Value of integer:%d",__bswap_32(f));
return 0;
}
我不确定这是否正好是 4 个字节。我尝试使用以下整数:
input->output
123->123
12345678->12345678
123456789->123456789
4294967295->-1
4294967294->-2
4294967296->-1
1->1
我认为通过打印 f
会像这样:1234000
(f=1234
的值)或 12345678
(f=123456789
的值)。
解决方法
要从 stdin
中准确读取 4 个字节,您可以使用 fread()
、getc()
或 scanf()
:
fread(&f,sizeof f,1,stdin);
char *p = (char *)&f; for (size_t i = 0; i < sizeof(f); i++) p[i] = getchar();
char *p = (char *)&f; for (size_t i = 0; i < sizeof(f); i++) p[i] = getc(stdin);
char *p = (char *)&f; scanf("%c%c%c%c",p,p+1,p+2,p+3);
但是请注意,stdin
在执行行结束转换的旧系统上默认以文本模式打开,并且没有可移植的方式在打开的流上更改此模式。