Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary stdin and 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.

like image 591
Rich Avatar asked Dec 23 '22 08:12

Rich


1 Answers

In Perl, you could just try:

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

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. :)

#include <stdio.h>

int main () {
   int x;

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

   return 0;
}
like image 184
Jeremy Bourque Avatar answered Jan 05 '23 17:01

Jeremy Bourque