C了解二进制标准输入 [英] C read binary stdin

查看:114
本文介绍了C了解二进制标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个指令流水线模拟器和我有很多的麻烦开始。我需要做的是阅读从标准输入的二进制,然后将其存储在内存中以某种方式,而我操纵数据。我需要一后正好在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,0,0,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 [] 好吗?

编辑:我能够读取该二进制文件,但没有一个答案产生正确的顺序位 - 他们都错位了,我怀疑字节顺序和问题读,在走动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 ... <一个href=\"http://stackoverflow.com/questions/1614399/c-endian-conversion-bit-by-bit/1615275#1615275\">http://stackoverflow.com/questions/1614399/c-endian-conversion-bit-by-bit/1615275#1615275

I had it right the first time, except, I needed ntohl ... http://stackoverflow.com/questions/1614399/c-endian-conversion-bit-by-bit/1615275#1615275

这篇关于C了解二进制标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆