从C中的标准输入读取N个字节
我必须从标准输入中准确读取4个字节,然后将其视为一个小的endian,并在标准输出中显示它,但我不知道我读取的是否准确为4个字节。我试过这个:从C中的标准输入读取N个字节,c,byte,bit,uint32-t,C,Byte,Bit,Uint32 T,我必须从标准输入中准确读取4个字节,然后将其视为一个小的endian,并在标准输出中显示它,但我不知道我读取的是否准确为4个字节。我试过这个: #include <stdio.h> #include <stdint.h> #include <inttypes.h> #include <byteswap.h> int main() { uint32_t f; printf("Enter a value :");
#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;
}
我想通过打印
f
它会像这样:1234000
(f=1234的值)或12345678
(f=123456789的值)。要从stdin
中准确读取4个字节,可以使用fread()
、getc()或f()
:
fread(&f,sizeof,1,stdin)代码>
char*p=(char*)&f;对于(size_t i=0;i
char*p=(char*)&f;对于(size_t i=0;i
char*p=(char*)&f;scanf(“%c%c%c%c”,p,p+1,p+2,p+3)代码>
但是请注意,在执行行结束翻译的传统系统上,默认情况下,stdin
在文本模式下是打开的,并且没有可移植的方法在开放流上更改此模式。%d
打印签名的int
,试试%u
。我刚用%u
试过,结果还是一样。你是说你仍然得到4294967295
->-1
<代码>%u
无法输出负值。你想做什么还不太清楚。对不起,你说得对!我尝试使用123456789
而不是4294967295
。如果我尝试使用4294967296
我仍然得到4294967295
,我认为这是正确的。非常感谢。
input->output
123->123
12345678->12345678
123456789->123456789
4294967295->-1
4294967294->-2
4294967296->-1
1->1