Binary stdin and stdout

I'm going to write a couple of utilities that read in a list of integers separated by a new line on stdin and print their binary (4 bytes) equivalent to stdout and vice versa.

My first thought was a simple bash / linux command that would do this, but I could not find it. 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 am impartial to any particular programming language.

+3
source share
3 answers

In Perl, you can just try:

perl -ne 'chomp; print pack 'i', $_;'

32 , , , C.

'i', 'l', , 32-. little-endian big-endian.

http://perldoc.perl.org/functions/pack.html.

C, . :)

#include <stdio.h>

int main () {
   int x;

   while (fscanf(stdin, "%i", &x)) {
      fwrite(&x, sizeof(x), 1, stdout);
   }

   return 0;
}
+5

" stdout ", . , , , . , , .

fscanf() , fwrite() , . , .

+4

On Unix and its derivatives, there is no need to worry about whether stdin or stdout are β€œbinary” modes β€” the binary and text modes are the same. I did not do extensive testing on Windows, but under Cygwin I also did not notice any problems.

+1
source

Source: https://habr.com/ru/post/1718545/


All Articles