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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With