问题描述
我正在尝试构建一个指令管道模拟器,但我在开始时遇到了很多麻烦.我需要做的是从标准输入读取二进制文件,然后在我操作数据时以某种方式将其存储在内存中.我需要一个接一个地读取正好 32 位的块.
I'm trying to build an instruction pipeline simulator and I'm having a lot of trouble getting started. What I need to do is read binary from stdin, and then store it in memory somehow while I manipulate the data. I need to read in chunks of exactly 32 bits one after the other.
如何一次读取正好 32 位的块?其次,我如何存储它以供以后操作?
How do I read in chunks of exactly 32 bits at a time? Secondly, how do I store it for manipulation later?
这是我到目前为止所得到的,但是检查我进一步阅读的二进制块,它看起来不正确,我认为我没有像我需要的那样准确地读取 32 位.
Here's what I've got so far, but examining the binary chunks I read further, it just doesn't look right, I don't think I'm reading exactly 32 bits like I need.
char buffer[4] = { 0 }; // initialize to 0
unsigned long c = 0;
int bytesize = 4; // read in 32 bits
while (fgets(buffer, bytesize, stdin)) {
memcpy(&c, buffer, bytesize); // copy the data to a more usable structure for bit manipulation later
// more stuff
buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0; // set to zero before next loop
}
fclose(stdin);
我如何一次读取 32 位(它们都是 1/0,没有换行符等),我将它存储在什么中,char[]
好吗?
How do I read in 32 bits at a time (they are all 1/0, no newlines etc), and what do I store it in, is char[]
okay?
我能够读取二进制文件,但没有一个答案以正确的顺序产生位 - 它们都被弄乱了,我怀疑字节顺序和读取和移动 8 位(1 个字符)的问题时间——这需要在 Windows 和 C 上工作......?
I'm able to read the binary in but none of the answers produce the bits in the correct order — they are all mangled up, I suspect endianness and problems reading and moving 8 bits around ( 1 char) at a time — this needs to work on Windows and C ... ?
推荐答案
我第一次做对了,除了,我需要 ntohl ... C 端转换:逐位
I had it right the first time, except, I needed ntohl ... C Endian Conversion : bit by bit
这篇关于C读取二进制标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!