二进制标准输入和标准输出
我正在寻找编写一对实用程序,它们在 stdin 上读取换行符分隔的整数列表,并输出相当于 stdout 的二进制(4 字节),反之亦然。
我的第一个想法是一个简单的 bash/linux 命令可以做到这一点,但我找不到一个。我的第二个想法是在 C++ 中执行此操作,但我不知道如何将 stdin 或 stdout 更改为二进制流。
有什么好的方法可以做到这一点吗?我对任何特定的编程语言都是公正的。
I'm looking to write a pair of utilities that read in a newline separated list of integers on stdin and output their binary (4 byte) equivalent to stdout, and vice versa.
My first thought was a simple bash/linux command that would do this, but I was unable to find one. My second thought was to do this in C++, but I can't figure out how to change stdin or stdout to a binary stream.
Any thoughts on a good way to do this? I'm impartial to any particular programming language.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Perl 中,您可以尝试:
这将为您提供一个至少 32 位的主机本机有符号整数,但可能更多,具体取决于您本地的 C 编译器。
其他要打包的选项可以代替
'i'
,例如'l'
将为您提供一个带符号的 long,它应该是 32 位。对于小端或大端还有更多选择。有关完整说明,请参阅 http://perldoc.perl.org/functions/pack.html 。
这是你的 C 解决方案,以防你想用无聊的方式来做。 <代码>:)
In Perl, you could just try:
That will give you a host native signed integer of at least 32 bits, but possibly more depending on your local C compiler.
Other options to pack can go in place of the
'i'
, such as'l'
which will give you a signed long, which should be 32-bits. And there yet more options for little-endian or big-endian.For the full description, please see http://perldoc.perl.org/functions/pack.html.
And here's your solution in C, in case you want to do it the boring way.
:)
您不需要“将标准输出更改为二进制”,只需向其输出二进制即可。这肯定会混淆例如连接到该流的终端仿真器,但这是可以预料的。
使用
fscanf()
的普通循环读取每个整数,然后使用fwrite()
将其写出应该可以工作。但要注意字节顺序问题,您可能希望单独输出每个字节。You don't need to "change stdout to binary", just output binary to it. This will certainly confuse e.g. a terminal emulator connected to that stream, but that is to be expected.
A plain loop of
fscanf()
to read each integer, followed by afwrite()
to write it out should work. Beware of endianness issues though, you might want to output each byte separately.在 Unix 及其衍生版本上,无需关心 stdin 或 stdout 是否为“二进制”模式 - 二进制和文本模式是相同的。我没有在 Windows 上进行广泛的测试,但在 Cygwin 下,我也没有注意到那里有任何问题。
On Unix and its derivatives, there is no need to be concerned about whether the stdin or stdout are 'binary' mode - binary and text modes are the same. I've not conducted extensive testing on Windows, but under Cygwin, I've not noticed any issues there, either.